knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(dplyr) library(purrr) library(ggplot2) library(ggsubplot2)
d1 = mtcars %>% group_nest(gear, cyl) %>% mutate(plot = map(data, ~ ggplot(.x, aes(x = mpg)) + geom_density() )) ggplot(d1, aes(x = gear, y = cyl, plot = plot)) + geom_subplot(width = 0.75, height = 0.75) # use a subplot theme ggplot(d1, aes(x = gear, y = cyl, plot = plot)) + geom_subplot(width = 0.75, height = 0.75, theme = theme_bw(base_size = 8)) # standardize plots ggplot(d1, aes(x = gear, y = cyl, plot = plot)) + geom_subplot(width = 0.75, height = 0.75, theme = list( theme_bw(base_size = 8), ylab(NULL), ylim(c(0, 1)), xlim(c(10, 35)) ))
d2 = mtcars %>% group_nest(am, vs, cyl, gear) %>% mutate( plot = map(data, ~ ggplot(.x) + aes(x = wt, y = mpg) + geom_point() )) ggplot(d2, aes(x = gear, y = cyl, plot = plot)) + facet_grid(vs ~ am) + geom_subplot(width = 0.75, height = 0.75) # flipping will not flip the plots ggplot(d2, aes(x = gear, y = cyl, plot = plot)) + facet_grid(vs ~ am) + geom_subplot(width = 0.75, height = 0.75, theme = theme()) coord_flip()
library(sf) nc <- st_read(system.file("shape/nc.shp", package = "sf")) data(Crime, package = "Ecdat") crimedat = Crime %>% group_nest(county) %>% mutate(plot = map(data, ~ ggplot(.x, aes(x = year, y = crmrte)) + geom_line(color = "red") )) ncdat = nc %>% st_transform(3857) %>% bind_cols(as_tibble(st_coordinates(st_centroid(.)))) %>% left_join(crimedat, by = c("CRESS_ID" = "county")) ggplot(ncdat) + geom_sf() + geom_subplot(aes(x = X, y = Y, plot = plot), width = 16000, height = 16000, theme = theme_void())
library(tidygraph) library(ggraph) set.seed(42) g = tbl_graph( nodes = tibble(x = sample(seq(1, 100, by = 5), 6), y = sample(seq(1, 100, by = 5), 6)), edges = tibble(from = sample(1:3, 3), to = sample(4:6, 3)) ) %N>% mutate(plot = map(1:n(), ~ ggplot(tibble(x = rnorm(1000, sd = .x)), aes(x = x)) + geom_histogram() )) ggraph(g, layout = "manual", x = x, y = y) + theme_graph() + geom_edge_link() + geom_node_tile(width = 10, height = 10) + geom_subplot(aes(x = x, y = y, plot = plot), width = 10, height = 10)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.