Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot vertically justify legend

Tags:

r

ggplot2

I've been looking at this for awhile now. My legends are running out of the chart area. Is there a way to vertically justify legend in ggplot2?

library(ggplot2)
df <- data.frame(x = 1:30, y = 1:30, color = letters[1:30])
ggplot(df, aes(x, y)) +
    geom_point(aes(colour = color)) +
    guides(col = guide_legend(nrow = 30))
like image 663
user1471980 Avatar asked Aug 30 '12 19:08

user1471980


1 Answers

Playing around with legend.direction ("vertical"/"horizontal") should work:

library(ggplot2)
df <- data.frame(x = 1:30, y = 1:30, color = letters[1:30])
ggplot(df, aes(x, y)) +
    geom_point(aes(colour = color)) +
    theme(legend.direction='horizontal')

You may also want to combine it with legend.box("horizontal"/"vertical").

If you want to control the absolute position of the legend, add:

theme(legend.direction = "vertical",
legend.box = "horizontal",
legend.position = c(0.025,0.975),
legend.justification = c(0, 1))

Which, for example, places the legend inside the top left corner of the graph.

like image 130
Nicholas Hamilton Avatar answered Dec 18 '22 22:12

Nicholas Hamilton