Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change legend title in ggplot

Tags:

plot

r

ggplot2

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?

enter image description here

like image 865
neversaint Avatar asked Jan 31 '13 09:01

neversaint


People also ask

How do I change the legend title 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 my legend title?

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.

How do you change the legend in R?

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.

How do I create a legend in ggplot2?

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.


1 Answers

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") 
like image 132
Arun Avatar answered Oct 15 '22 11:10

Arun