Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the legend title in ggplot2?

Tags:

r

legend

ggplot2

I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

carrots<-NULL carrots$Farm<-rep(c("X","Y"),2) carrots$Type<-rep(c("Orange","Purple"),each=2) carrots$MeanLength<-c(10,6,4,2) carrots<-data.frame(carrots) 

I make a simple bar plot:

require(ggplot2) p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +  geom_bar(position="dodge") + opts(legend.position="top") p 

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

like image 238
susjoh Avatar asked May 16 '11 20:05

susjoh


People also ask

How do you remove legend titles?

To remove legend title, its legend. title attribute is set to element_blank(). Example: Removing legend title with theme().

How do I get rid of the legend in ggplot2?

Example 1: Remove All Legends in ggplot2 We simply had to specify legend. position = “none” within the theme options to get rid of both legends.

How do I change my legend name in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


2 Answers

I found that the best option is to use + theme(legend.title = element_blank()) as user "gkcn" noted.

For me (on 03/26/15) using the previously suggested labs(fill="") and scale_fill_discrete("") remove one title, only to add in another legend, which is not useful.

like image 197
Tom B. Avatar answered Sep 28 '22 02:09

Tom B.


You can modify the legend title by passing it as the first parameter to a scale. For example:

ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) +    geom_bar(position="dodge") +   theme(legend.position="top", legend.direction="horizontal") +   scale_fill_discrete("") 

There is also a shortcut for this, i.e. labs(fill="")

Since your legend is at the top of the chart, you may also wish to modify the legend orientation. You can do this using opts(legend.direction="horizontal").

enter image description here

like image 45
Andrie Avatar answered Sep 28 '22 03:09

Andrie