Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating columns within a legend list while using ggplot in R code

Tags:

r

ggplot2

I am plotting 15 lines using ggplot (package name: ggplot2), each representing a separate entity and wish to create a legend for the same. However, I am not able to divide the legend entries into more than one column. Can someone please suggest how to do the same in ggplot environment.

Presently, I am using the following command to create legend:

opts(title=plotName,legend.position='bottom')

However, this gives a one column legend. As a result a large area in the chart is taken by legend itself. Dividing it into 2 or 3 columns would really help the cause while keeping the legend at the bottom of the chart. I also tried legend.direction but this command displays legend in one row which is not desirable either unless I may spread it across 2-3 rows.

opts(title=plotName,legend.position='bottom',legend.direction="horizontal")

Thanks in advance, Munish

like image 406
Munish Avatar asked Jun 22 '12 19:06

Munish


2 Answers

Using the new themes environment of ggplot requires only a simple: + guides(col=guide_legend(ncol=2)) to format your legend in 2 columns.

like image 93
user2399309 Avatar answered Nov 14 '22 14:11

user2399309


You can use guide_legend() to control the layout and appearance of ggplot legends. In particular, it takes arguments nrow and ncol, which are what you're after.

Here's an example taken from Section 2 of the very helpful document Changes and additions to ggplot2-0.9.0.pdf.

library(ggplot2)

q <- ggplot(diamonds, aes(x = table, fill = clarity)) +
     geom_histogram() +
     scale_y_continuous()

q + guides(fill = guide_legend(nrow = 4, title.hjust = 0.4,
        title.theme = theme_text(size = 12, face = "bold"))) +
xlim(45, 75)
like image 25
Josh O'Brien Avatar answered Nov 14 '22 14:11

Josh O'Brien