I got intensely curious about this, but found that my go-to, cowplot
, wouldn't quite space the plots properly. The package writer himself suggested using patchwork
instead for more complex spacing and alignment. With cowplot
, I'd made a dummy ggplot
to hold the top right as a blank space, but couldn't get the heights right. patchwork
instead has a plot_spacing
function to do this.
The first task was to make a summary data frame for drawing the lines. I added a row number so there was a way to stack the lines vertically for the top margin, and horizontally for the right margin. (I suppose a dummy value and position_dodge
may have worked also.)
library(tidyverse)
library(patchwork)
summaries <- mtcars %>%
group_by(gear) %>%
summarise(minwt = min(wt), maxwt = max(wt), minmpg = min(mpg), maxmpg = max(mpg)) %>%
ungroup() %>%
mutate(row = row_number())
summaries
#> # A tibble: 3 x 6
#> gear minwt maxwt minmpg maxmpg row
#> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
#> 1 3 2.46 5.42 10.4 21.5 1
#> 2 4 1.62 3.44 17.8 33.9 2
#> 3 5 1.51 3.57 15 30.4 3
I made the top and right plots, using the same ggplot
base, and gave them theme_void
so there would be nothing shown except the segments themselves. I'd suggest going through this with a different theme so you can see how the plots come together.
summary_base <- ggplot(summaries, aes(color = factor(gear)))
top <- summary_base +
geom_segment(aes(x = minwt, xend = maxwt, y = row, yend = row), show.legend = F) +
theme_void()
right <- summary_base +
geom_segment(aes(x = row, xend = row, y = minmpg, yend = maxmpg), show.legend = F) +
theme_void()
Then the main plot:
points <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) +
geom_point() +
theme(legend.position = "bottom")
Then patchwork
allows you to just add the plots together. They go left to right, top to bottom, so to get the top right blank space, I used plot_spacer
. Then plot_layout
sets up the grid. You can adjust the relative heights and widths how you want—probably make them more narrow. This was my first time using patchwork
, but it was very straightforward.
top + plot_spacer() + points + right +
plot_layout(ncol = 2, nrow = 2, widths = c(1, 0.2), heights = c(0.2, 1))

Created on 2018-07-11 by the reprex package (v0.2.0).