arranging ggplot2 legend items in a grid

I have a legend with 4 different entries that I would like to arrange in a 2x2 grid instead of horizontally or vertically. I'm extracting the legend for separate use, which is why I need this somewhat unusual arrangement. Any ideas?

The code below generates the legend with all entries vertically in a single column:

require(ggplot2)
library(grid)
library(gridExtra)

dat <- data.frame(x=c(1,2,1,2,1,2,1,2),y=c(1,2,3,4,2,3,4,5),color=factor(c("a","a","b","b","c","c","d","d")))
p = ggplot(dat)
p = p + geom_line(aes(dat$x,dat$y,color=dat$color))
p = p + scale_colour_manual (values=dat$color,name="")
#print(p)

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

legend <- g_legend(p)
grid.arrange(legend)

Answers


Try adding guides(colour = guide_legend(nrow = 2)) to your plot.


Need Your Help

override namespaced puts only works after overriding Kernel.puts?

ruby override puts

Sorry for the vague question title, but I have no clue what causes the following:

Get message in Java code ( Spring 3 )

spring spring-mvc properties annotations messages

&lt;bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.