Last active
February 18, 2020 10:31
-
-
Save favstats/735d0d1184532e826c52623aebe03d03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Install these packages if you don't have them yet | |
# if (!require("pacman")) install.packages("pacman") | |
pacman::p_load(tidyverse, egg, gridExtra, grid, patchwork) | |
## Function to fix panel width and add "buffers" for right-alignment | |
## based on: https://gist.github.com/baptiste/eadeecd7d3756a7f294eb3cade8b0b17 | |
facet_cleaner <- function(p, panel_size = 5, panel_height = 1) { | |
p %>% | |
egg::set_panel_size( | |
width = grid::unit(panel_size,'cm'), | |
height = grid::unit(panel_height,'null')) %>% | |
gridExtra::arrangeGrob(grid::rectGrob(gp=grid::gpar(col=NA)), ., nrow=1, | |
widths = grid::unit.c(grid::unit(1,'null'), sum(.$widths))) | |
} | |
## Create dataset with two groups | |
d <- tibble::tibble(vals = runif(200, 0, 10), | |
group1 = rep(c("Germany", "United Kingdom", | |
"France", "Belgium", | |
"Netherlands", "USA", | |
"Russia", "Spain"), 25)) %>% | |
dplyr::mutate(group2 = dplyr::case_when( | |
group1 %in% c("Germany", "France", "USA") ~ "Group A", | |
group1 %in% c("Spain", "United Kingdom")~ "Group B", | |
T ~ "Group C")) %>% | |
dplyr::group_by(group1) %>% | |
dplyr::mutate(order = 1:dplyr::n()) %>% | |
dplyr::ungroup() | |
## ggplot | |
d %>% | |
## split by row group | |
dplyr::group_split(group2) %>% | |
## plot each row individually | |
purrr::map(~{ | |
.x %>% | |
ggplot2::ggplot(ggplot2::aes(order, vals)) + | |
ggplot2::geom_line() + | |
ggplot2::facet_grid(group2~group1) | |
}) %>% | |
## fix facet width and add buffer | |
purrr::map(facet_cleaner) %>% | |
## plot grobs on top of each other | |
patchwork::wrap_plots(ncol = 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: