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!
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.
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".
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With