I am trying to control spacing and labels in a ggplot graph formed with facet_grid. I have made some research and I am using arguments that I thought would help me achieve at least the first objective but the result is not what I expected.
For a reproducible example I use the mtcars dataset (base R) and I provide an image of the output of the code where I indicate what I would like to be changed.
Your advice will be appreciated.
data(mtcars)
setDT(mtcars)
mtcars[, ":="(vs = as.factor(vs), am = as.factor(am), gear = as.factor(gear), carb = as.factor(carb))]
ggplot (mtcars,
aes(x= disp , y = hp , colour = carb)) +
geom_point (size = 2) + facet_grid ( gear ~ vs * am , margins = TRUE) +
xlab('disp') + ylab('hp') +
theme(panel.spacing.x=unit(2, "lines"), panel.spacing.y=unit(2, "lines"))+
theme_economist() + theme(plot.margin = unit(c(1, 1, 1, 1), "lines"))
The space between panels you can define with parameter panel.spacing
in theme
. The theme_economist
is changing it. By default there are spaces between panels.
You can also add the labeller function label_both
in order to have the variable names on each panel label.
ggplot (mtcars,
aes(x= disp , y = hp , colour = carb)) +
geom_point (size = 2) + facet_grid ( gear ~ vs * am , margins = TRUE, labeller = label_both) +
xlab('disp') + ylab('hp') +
theme(panel.spacing.x=unit(2, "lines"), panel.spacing.y=unit(2, "lines"))+
theme_economist() + theme(plot.margin = unit(c(1, 1, 1, 1), "lines"), panel.spacing=unit(2,"lines"))