Skip to content

Instantly share code, notes, and snippets.

@kohske
Created August 11, 2011 14:48
Show Gist options
  • Save kohske/1139848 to your computer and use it in GitHub Desktop.
Save kohske/1139848 to your computer and use it in GitHub Desktop.
ggplot2: example codes for matrix-like legend guide
p <- qplot(1:20, 1:20, col=letters[1:20])
p + guides(col=guide_legend(nrow=8))
p + guides(col=guide_legend(ncol=8))
p + guides(col=guide_legend(nrow=8, byrow=T))
p + guides(col=guide_legend(ncol=8, byrow=T))
# output plots: http://yfrog.com/klhjpwp
# how to embed images in gist...?
# you can install very very easily the develop version of ggplot2 on github thanks to Hadley's devtools package.
install.packages('devtools')
install.packages(c("RColorBrewer", "stringr", "dichromat", "munsell", "plyr", "colorspace")) # probably windows only
library(devtools)
dev_mode(TRUE)
install_github("scales")
install_github("ggplot2", "kohske", "feature/new-guides-with-gtable")
library(ggplot2)
@GregoryEady
Copy link

Excellent. Thanks for the quick response.

@GregoryEady
Copy link

The "cutting-edge" version seemed to fix the problem.

Two small(ish) problems with the ways the legend is now constructed with guides():

It seems that the legend labels are now centered rather than left-justified as they were before. I wonder if there is a parameter to put the labels back to left justification.

Also, when I set the legend.position to "bottom", the legend ends up in the bottom right hand corner of the plot window, rather than at the bottom and centered as it is in the official version.

My code is as follows:

ggplot(Dataset) +
my.theme(base_size = textsize) +
stat_density(aes(x = theAnswer, colour = theGroup, order = as.factor(theGroup)), size = 1, adjust = smooth, geom = "path", position = "identity") +
#facet_wrap(~question) +
coord_cartesian(xlim = c(0.5,5.5)) +
scale_x_continuous(breaks = c(1,2,3,4,5),
labels = answerLabels[(answer_5-4):(answer_5)]) +
scale_y_continuous(breaks = NA) +
labs(x = NULL, y = NULL, colour = "") +
opts(legend.position = "bottom",
legend.direction = "horizontal",
legend.key.size = unit((textsize/13), "lines"),
panel.background = theme_rect(fill = "grey14", colour = "grey14"),
plot.background = theme_rect(colour = "grey14"),
panel.border = theme_rect(fill = NA, colour = "grey90", size = 1.25),
plot.margin = unit(c(0, 7, 0, 5.5), "lines")) +
scale_colour_manual(breaks = legendOrder, values = color) +
guides(col=guide_legend(ncol=3))

Thanks again!

@kohske
Copy link
Author

kohske commented Nov 18, 2011

could you please provide a reproducible example?
?guide_legend will show you help page.

@liamxg
Copy link

liamxg commented Oct 17, 2022

how can i set the legend row into one?

@liamxg
Copy link

liamxg commented Oct 17, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment