Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding facet titles and changing legend title in ggplot2

Tags:

r

ggplot2

I wonder how to add facet titles in ggplot2

ggplot(diamonds, aes(cut)) + geom_bar() +   facet_grid(color ~ clarity)

and change the legend title

ggplot(diamonds, aes(cut, fill=cut)) + geom_bar() +   facet_grid(. ~ clarity)

Thanks for your help.

like image 888
MYaseen208 Avatar asked Sep 29 '11 22:09

MYaseen208


People also ask

How do I change the legend title in ggplot2?

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

How do I add a legend in ggplot2?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.


1 Answers

The facets are labeled using the levels of the factor used. So if you simply change the levels , such as

levels(diamonds$clarity) <- letters[1:8]

those facets will now be labeled using those letters. The legend title matches the label for that aesthetic mapping, which you can set via:

+ labs(fill = "Fill legend label")

As an extra tidbit, I've noticed that I can set the x and y axis labels to NULL in labs but not the legend titles; for those you use an empty character if you want no title.

Edit

Given your clarifications, you can add text outside the plotting area using grid.text:

print(qplot(1,1),vp = viewport(width = 0.9))
grid.text(unit(0.95,"npc"),0.5,label = "Right label", rot = 270)

enter image description here

like image 87
joran Avatar answered Nov 04 '22 13:11

joran