Skip to content

Instantly share code, notes, and snippets.

@baptiste
Last active October 10, 2017 19:19
Show Gist options
  • Save baptiste/960186a01ca3c48b112f4a15fe013884 to your computer and use it in GitHub Desktop.
Save baptiste/960186a01ca3c48b112f4a15fe013884 to your computer and use it in GitHub Desktop.
what if ggplot guides were ggplots
library(ggplot2)
library(grid)
d <- data.frame(x=rnorm(50), y=rnorm(50), f1 = rep(gl(5,5), 2), f2 = gl(2, 25))
p <- ggplot(d, aes(x,y, group=interaction(f1,f2))) +
geom_line(aes(colour=f1, linetype=f2)) +
geom_point(aes(colour=f1, shape=f1))
gb <- ggplot_build(p)
pp <- gb$plot
th <- theme_grey() + theme(legend.direction = "vertical")
gdefs <- ggplot2:::guides_train(scales = pp$scales, theme = th, guides = pp$guides,
labels = pp$labels)
legs <- lapply(gdefs, "[[", "key")
names(legs) <- c("point", "segment", "point")
make_guide <- function(d, title){
map <- list(as.symbol(colnames(d)[1]))
names(map) <- colnames(d)[1]
class(map) <- "uneval"
ggplot(d, aes(x=0,y=0)) + facet_grid(.label~.) +
geom_point(map) +
scale_colour_identity() +
scale_shape_identity() +
scale_x_continuous(breaks=NULL)+
scale_y_continuous(breaks=NULL) +
labs(x=NULL, y=NULL) +
theme_minimal() +
theme(panel.background = element_rect(fill="grey95"),
legend.position = "none",
strip.text.y = element_text(angle=0)) +
ggtitle(title)
}
pl <- Map(make_guide, legs, names(legs))
pl <- lapply(pl, egg::set_panel_size, width=unit(1,"line"), height=unit(1,"line"))
gridExtra::grid.arrange(grobs = pl, ncol=1)
@baptiste
Copy link
Author

baptiste commented Apr 8, 2017

would require:

  • ability to set panel sizes, align them (I think egg has the right concept with 3x3 frames, but might be biased)
  • more orthogonal separation of tasks in ggplot_build, to train the scales on data independently of messy layout and theme business
  • some clever NSE tricks for aesthetics and geom types
  • a new function to merge guides
  • some decisions on user interface and constraints
  • think about colorbar scales

maybe easier to wrap it all in a separate package, kind of a stripped-down version of ggplot with no stats, coords, axes, guides.

@baptiste
Copy link
Author

baptiste commented Apr 9, 2017

preview

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