In the below coefficient plot, I would like to decrease the white space under "Roads" and "Timing" as highlighted in red:
How can I make this look tidier? Below is my current code, using ggplot2:
plotdata <- structure(
list(
term = c("Category 1_a","Category 1_b","Category 1_c","Category 1_d","Category 2",
"Category 3_a","Category 3_b"),
estimate = c(-0.033882004,0.001508041,0.122957935,-0.033882004,0.001508041,-0.033882004,0.001508041),
ymin = c(
-0.13278953,-0.007547426,0.025116265,-0.13278953,-0.007547426,-0.13278953,-0.007547426), ymax = c(0.065025521,0.010563508,0.220799605,0.065025521,0.010563508,0.065025521,0.010563508)
), row.names = c(NA,-7L),
spec = structure(list(cols = list(
term = structure(list(), class = c("collector_character",
"collector")),
estimate = structure(list(), class = c("collector_double",
"collector")),
ymin = structure(list(), class = c("collector_double",
"collector")),
ymax = structure(list(), class = c("collector_double",
"collector"))
),
default = structure(list(), class = c("collector_guess",
"collector")),
delim = ","), class = "col_spec"),class = c("spec_tbl_df","tbl_df", "tbl", "data.frame"))
# Libraries
library(dplyr)
library(broom)
library(ggplot2)
# Plot
plotdata %>%
mutate(category = rep(c("Pollution", "Roads", "Timing"), times = c(4, 1, 2))) %>%
mutate(term = factor(term, levels = rev(term))) %>%
ggplot(aes(x = term, y = estimate))
geom_hline(yintercept = 0, color="black", size = 0.5, linetype = "dashed")
geom_pointrange(aes(ymin = ymin, ymax = ymax), size = 0.5,
fill="#0202fe", color="#b5b5b5", shape=21, stroke = 1)
labs(x = NULL, y = "Coefficient Estimate")
scale_x_discrete(expand = c(0.4, 0.1))
coord_flip()
facet_grid(category~., switch = 'y', scales = 'free_y')
theme_classic(base_size = 13)
theme(strip.placement = 'outside',
strip.background = element_blank(),
strip.text.y.left = element_text(face = 'bold', angle = 0, vjust = 1, hjust = 1),
panel.spacing.y = unit(0, 'mm'))
CodePudding user response:
This could be achieved via the space
argument of facet_grid
. Setting space="free_y"
will set the panel size according to the "proportional to the length of the y scale", i.e. the number of categories:
Note: I also dropped the scale_x_discrete
.
library(dplyr)
library(broom)
library(ggplot2)
# Plot
plotdata %>%
mutate(category = rep(c("Pollution", "Roads", "Timing"), times = c(4, 1, 2))) %>%
mutate(term = factor(term, levels = rev(term))) %>%
ggplot(aes(x = term, y = estimate))
geom_hline(yintercept = 0, color="black", size = 0.5, linetype = "dashed")
geom_pointrange(aes(ymin = ymin, ymax = ymax), size = 0.5,
fill="#0202fe", color="#b5b5b5", shape=21, stroke = 1)
labs(x = NULL, y = "Coefficient Estimate")
coord_flip()
facet_grid(category~., switch = 'y', scales = 'free_y', space = "free_y")
theme_classic(base_size = 13)
theme(strip.placement = 'outside',
strip.background = element_blank(),
strip.text.y.left = element_text(face = 'bold', angle = 0, vjust = 1, hjust = 1),
panel.spacing.y = unit(0, 'mm'))