Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the layout of ggplot legend

Tags:

r

ggplot2

I am curious if it is possible to change the layout of the ggplot legend without having to rewrite the build_legend function?

For example:

I want a 2 * 2 layout

a b
c d

rather than the normal 1 * 4 or 4 * 1 layout.

a b c d

or

a
b
c
d

Many Thanks,

MK

like image 291
MKao Avatar asked Nov 08 '11 10:11

MKao


People also ask

How do I change the position of my legend in R?

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.

How do I change the legend value 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 change the order of variables in legend ggplot2?

You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...) The following example shows how to use this syntax in practice.


2 Answers

I don't actually think this is possible with ggplot2, you really only have two options - horizontal or vertical. If you want to create something fancier, you'd have to do it yourself by creating a subplot with the same colour scheme, resizing and overlaying it onto your plot (I would envision something like a small facet_grid() placed wherever it may be appropriate).

... + opts(legend.direction="horizontal")
... + opts(legend.direction="vertical")
like image 127
Brandon Bertelsen Avatar answered Sep 30 '22 01:09

Brandon Bertelsen


Kohske has posted the solution to the problem, although it will not be available until the next version of ggplot.

qplot(1:4, 1:4, colour = letters[1:4]) + guides(colour = guide_legend(nrow = 2, byrow = T))
like image 41
MKao Avatar answered Sep 30 '22 02:09

MKao