Changing legend names without changing colors in ggplot2
ggplot2, r
Solution
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"))
Problem
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!