How to change labels (legends) in ggplot?

前端 未结 2 1023
臣服心动
臣服心动 2021-01-16 03:13

My code is like below, I want to change the label of the ggplot, but R always remind me:

Error in unit(tic_pos.c, \"mm\") : \'x\' and \'units\' must have len         


        
2条回答
  •  我在风中等你
    2021-01-16 04:14

    As a complement to @jlhoward's answer, scale_color_manual() is more intended to customize the color scale (the actual colors that will be displayed).

    For your case, you might rather use scale_color_discrete():

    ggplot(mtcars, aes(x=hp,color=factor(cyl)))+
        geom_density()+
        scale_color_discrete(name="Cylinders",
                             labels=c("4 Cylinder","6 Cylinder","8- Cylinder"))
    

    This is quicker, but it is dependant on the factor levels order, which might lead to irreproducibility. You might want to specify the breaks argument to minimise the risk of error (and customize the order in the legend):

    ggplot(mtcars, aes(x=hp,color=factor(cyl)))+
        geom_density()+
        scale_color_discrete(name="Cylinders",
                             breaks=c(8,6,4),
                             labels=c("8 Cylinder","6 Cylinder","4 Cylinder"))
    

    More info on https://ggplot2-book.org/scales.html.

提交回复
热议问题