How to change labels (legends) in ggplot?

33,577

Solution 1

Is mat$type a factor? If not, that will cause the error. Also, you can't use labels(...) this way.

Since you did not provide any data, here's an example using the built-in mtcars dataset.

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

In this example,

ggplot(mtcars, aes(x=hp,color=cyl))+...

would cause the same error that you are getting, because mtcars$cyl is not a factor.

Solution 2

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.

Share:
33,577

Related videos on Youtube

Chen
Author by

Chen

A little white mouse searching for the big cheese.

Updated on July 05, 2022

Comments

  • Chen
    Chen almost 2 years

    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 length > 0
    

    What should I do?

    ggplot(mat,aes(x=sales,col=type))+
      geom_density()+labels("red_sold","blue_sold","yellow_sold")
    
  • Dan Chaltiel
    Dan Chaltiel almost 5 years
    Of note, it is possible to change name and labels with keeping the defaults values by using scale_color_discrete() instead.
  • Fabian Winkler
    Fabian Winkler almost 4 years
    @DanChaltiel Maybe you could post your comment as a regular answer, so it's easier to find?