简体   繁体   中英

How do you completely remove the spaces between facet strips (to connect a geom_rect 'background')?

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')
  )

由物种分面的虹膜箱线图,其中面板之间有一个小的灰色空间(geom_rect 未覆盖的位)。

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!

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')
  )

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM