Here's some toy data.
library(tidyverse)
df <- structure(list(district = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3,
3), office = c("GOV", "WAG", "USS", "WST", "GOV", "WAG", "USS",
"WST", "GOV", "WAG", "USS", "WST"), margin = c(-10.6296758104738,
-11.0540006895039, -16.2188249213812, -15.4710156423517, -12.7093173035638,
-12.9545865749955, -17.3703863277323, -17.4593332847035, -10.1910380671443,
-10.984606653898, -14.8799042051138, -15.8511248029804)), row.names = c(NA,
-12L), class = c("tbl_df", "tbl", "data.frame"))
> df
# A tibble: 12 × 3
district office margin
<dbl> <chr> <dbl>
1 1 GOV -10.6
2 1 WAG -11.1
3 1 USS -16.2
4 1 WST -15.5
5 2 GOV -12.7
6 2 WAG -13.0
7 2 USS -17.4
8 2 WST -17.5
9 3 GOV -10.2
10 3 WAG -11.0
11 3 USS -14.9
12 3 WST -15.9
I'd like to make a scatterplot of each combination of the values in the office
column. I want the plots to be a grid like this:
GOV WAG USS WST
GOV
WAG
USS
WST
Here is a kludgy version of what I mean, using a custom function and the {{patchwork}} package.
facet_office <- function(xoffice){
df %>%
group_by(district) %>%
mutate(x = margin[office == xoffice]) %>%
ggplot(aes(x, margin)) +
geom_point() +
scale_x_continuous(name = xoffice, limits = c(min(df$margin), max(df$margin))) +
scale_y_continuous(limits = c(min(df$margin), max(df$margin))) +
facet_grid(rows = ~office)
}
library(patchwork)
(facet_office("GOV") / facet_office("WAG") / facet_office("USS") / facet_office("WST"))
I'd like to do this in one step using ggplot2::facet_grid
, which requires both a row and column variable to be specified. I'd like to specify that each value in office
should be both a row and a column. The grid should contain each unique combination. Does anyone have a suggestion for a better way to do this?