Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ggplot2, how to change the legend labels but leave the colors unchanged?

Tags:

r

ggplot2

Given following ggplot diagram,

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl)))

If I want to change the labels of the legends, I can do the following:

p + scale_color_manual(labels = c("X", "Y", "Z"), values = 1:3)

But what should I do if I want to change the labels only and leave the colors unchanged? I've tried using the following formula:

p + scale_color_manual(labels = c("X", "Y", "Z"))

And it gives an error, saying: Error in f(...) : argument "values" is missing, with no default.

Of course, I can achieve this by setting the factor cyl:

mtcars$cyl = as.factor(mtcars$cyl, labels = c("X", "Y", "Z"))
ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl)))

But, I wondering whether it is possible to achieve this in scale_color_manual or in some other ways.

like image 921
Likan Zhan Avatar asked Aug 30 '25 18:08

Likan Zhan


1 Answers

How about scale_color_discrete

p + scale_color_discrete(labels=letters[1:3])
like image 140
MrFlick Avatar answered Sep 02 '25 07:09

MrFlick