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
How can I do it correctly?
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.
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.
Legend type guide shows key (i.e., geoms) mapped onto values. Legend guides for various scales are integrated if possible.
Right click legend, axis title or text object and choose Properties from context menu. On Frame tab, check Wrap Text, Adjust Height checkbox.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With