Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing legend names without changing colors in ggplot2

Tags:

r

ggplot2

I would like to rename the values in a legend without altering the custom colors that have already been set. Is there a way to set legend labels without using scale_color_manual? Currently, I have something like this:

norm <- rnorm(1000, 0 , .5)
gam <- rgamma(1000, 2)
beta <- rbeta(1000, 2, 3)
dist <- data.frame(Normal = norm, Gamma = gam, Beta= beta)
dat <- melt(dist, variable.name = "Distribution", value.name = "XValue")
plot1 <- ggplot(dat, aes(XValue, color = Distribution)) +
            stat_density(geom = "path", position = "identity", size = 2) +
            scale_color_manual(values = c("yellow", "black", "forestgreen"))

plot2 <- plot1 + scale_color_discrete(labels = c("Distribution 1",
                                "Distribution 2",
                            "Distribution 3"))

This however overwrites the manual colors. I will be changing the names in a different function from where I am setting colors so, unfortunately, I will not be able to use scale_color_manual( values =... , labels = ...). The other option I thought of is to somehow get the colors used in plot1. I could then do something like:

colors <- plot1$colors_used
plot2 <- plot1 + scale_color_manual(labels = c("Distribution 1", 
                                               "Distribution 2",
                        "Distribution 3"),
                                      values = colors)

Any help would be much appreciated. Thanks!

like image 860
Taylor Avatar asked Dec 12 '12 20:12

Taylor


People also ask

How do I change my legend name in ggplot2?

Method 1: Change Legend Title using guides() Function. Now if we want to change Legend Title then we have to add guides and guide_legend functions to the geom_point function. Inside guides() function, we take parameter named 'color' because we use color parameter for legend in ggplot() function.

How do I change the color of my legend in R?

To create the legend for a plot in base R, we can use legend function and if the background color of the legends needs to be changed from white to any other then bg argument in legend function will be used. For example, to change the background color to red then we can use bg="red".


1 Answers

It is possible to specify the label names in scale_colour_manual.

ggplot(dat, aes(XValue, color = Distribution)) +
  stat_density(geom = "path", position = "identity", size = 2) +
  scale_color_manual(values = c("yellow", "black", "forestgreen"),
                     labels = c("Distribution 1",
                                "Distribution 2",
                                "Distribution 3"))

enter image description here

like image 94
Sven Hohenstein Avatar answered Oct 14 '22 05:10

Sven Hohenstein