Reputation: 53
I would like to create a plot in R
with ggplot2
in which there are figure backgrounds using geom_rect
and also facetting to create nice labels (I think facet strips can be clearer than x-axis labels).
The issue I'm encountering is connecting the facet boxes together to remove any space between them. I tried to use theme(panel.spacing = unit(0 , 'lines')
however this doesn't completely remove the space between facet panels.
require(ggplot2)
#Create a numeric Species variable for positioning the geom_rect objects.
iris$Species_num <- as.integer(iris$Species)
p <- ggplot(iris,
aes(x = Species_num,
fill = Species,
y = Sepal.Length)
) +
#Use geom_rect to add a coloured background to each Species' boxplot.
geom_rect(
aes(
xmin = Species_num - .5,
xmax = Species_num + .5,
ymin = -Inf,
ymax = Inf,
fill = Species
),
alpha = .01
) +
geom_boxplot() +
facet_grid(~Species,
scales = 'free') +
#Replace the numeric x axis labels with the original Species labels.
scale_x_continuous(
breaks = unique(iris$Species_num),
labels = unique(iris$Species)
)
p + theme(
panel.spacing = unit(0,'lines')
)
Using negative values here causes the panels to infringe on the panel to its respective right-hand neighbouring panel, still with space between them.
p + theme(
panel.spacing = unit(-4,'lines')
)
Versions:
ggplot2_3.3.2
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Mojave 10.14.6
Thanks in advance for the help!
Upvotes: 2
Views: 4743
Reputation: 53
I think I may have just found the answer to this from: How to remove space between axis & area-plot in ggplot2?
The problem is the space between the plot and the axes. One can remove this by putting expand = c(0,0)
in the scale_x_continuous
bit.
p <- ggplot(iris,
aes(x = Species_num,
fill = Species,
y = Sepal.Length)
) +
geom_rect(
aes(
xmin = Species_num - .5,
xmax = Species_num + .5,
ymin = -Inf,
ymax = Inf,
fill = Species
),
alpha = .01
) +
geom_boxplot() +
facet_grid(~Species,
scales = 'free') +
scale_x_continuous(
breaks = unique(iris$Species_num),
labels = unique(iris$Species),
expand = c(0,0)
)
p + theme(
panel.spacing = unit(0,'lines')
)
Upvotes: 3