8

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

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

8

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)

2 Comments

The link is no more available. Any clue, where can I get the similar article?
@classy_BLINK Googling the name of the doc, I found a copy here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.