Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multi column legend in ggplot

Tags:

plot

r

ggplot2

I have the following script, which suppose to create a plot with two column legend.

 #!/usr/bin/Rscript library(ggplot2) library(plyr) library(reshape2) library(scales)  file <- "http://dpaste.com/1354089/plain/"; dat <-read.table(file,header=TRUE); datm <- melt(dat)  # Plot them ggplot(datm,aes(x = variable,y = value,fill = Term)) + geom_bar(position = "fill") + scale_y_continuous(labels = percent_format())+ theme(legend.direction ="vertical",legend.position = "bottom")+  guides(color=guide_legend(ncol=2))+ # this doesn't seem to work  ggsave(file="~/Desktop/test.pdf",width=11,height=11) 

But it creates this figure instead enter image description here

How can I do it correctly?

like image 815
pdubois Avatar asked Aug 23 '13 10:08

pdubois


People also ask

How to make legend two rows in ggplot?

If we want to draw ggplot2 Legend with two rows, we have to add guides and guide_legend functions to the theme() function. Inside guides() function, we take parameter named color, which has call to guide_legend() guide function as value.

How do I add a legend in ggplot2?

Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.

What does guides do in Ggplot?

Legend type guide shows key (i.e., geoms) mapped onto values. Legend guides for various scales are integrated if possible.

How do you wrap text in legend in R?

Right click legend, axis title or text object and choose Properties from context menu. On Frame tab, check Wrap Text, Adjust Height checkbox.


1 Answers

you must assign the guide to the correct aesthetic and you used fill:

guides(fill=guide_legend(ncol=2)) 

And you should take care of the warning with geom_bar

like image 174
Ido Tamir Avatar answered Sep 20 '22 16:09

Ido Tamir