I have the following plot like below. It was created with this command:
library(ggplot2) df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)), rating = c(rnorm(200), rnorm(200, mean=.8))) ggplot(df, aes(x=rating, fill=cond)) + geom_density(alpha = .3) + xlab("NEW RATING TITLE") + ylab("NEW DENSITY TITLE")
Now, I want to modify the legend title from cond into NEW LEGEND TITLE.
So, I just added the following line add the end of the above code:
+labs(colour="NEW LEGEND TITLE")
But it doesn't work. What's the right way to do it?
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.
Change the legend name using select dataSelect your chart in Excel, and click Design > Select Data. Click on the legend name you want to change in the Select Data Source dialog box, and click Edit. Note: You can update Legend Entries and Axis Label names from this view, and multiple Edit options might be available.
In order to change the legend size in R you can make use of the cex argument. Values bigger than 1 will lead to a bigger legend and smaller to smaller legends than the default.
Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.
This should work:
p <- ggplot(df, aes(x=rating, fill=cond)) + geom_density(alpha=.3) + xlab("NEW RATING TITLE") + ylab("NEW DENSITY TITLE") p <- p + guides(fill=guide_legend(title="New Legend Title"))
(or alternatively)
p + scale_fill_discrete(name = "New Legend Title")
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