In ggplot2 and facet_wrap, how to remove all margins and padding yet keep strip.text?

这一生的挚爱 提交于 2019-12-06 17:50:45

问题


This might primarily be a result of me misunderstanding how panel.margin = unit(...) works in the theme() function...but I'm unable to customize margins in facet_wrap the way that I'd like. Basically, I want a facet_grid that looks like this, with facet text (i.e. strip.text) inset in each facet and no spcaing between each facet:

(I've left in the pink borders to show the dimensions of each facet)

So here's the code so far.

To set up the data and plot:

library(ggplot2)
library(grid)
p <- ggplot() +
  geom_bar(data = mtcars, aes(x = cyl, y = qsec), stat = 'identity') +
  facet_wrap( ~ carb, ncol = 3)

mytheme <- theme_minimal() + theme(
  axis.text.x = element_blank(),
  axis.text.y = element_blank(),
  axis.ticks = element_blank(),
  axis.title = element_blank(),
  panel.margin = unit(0, "lines"),
  panel.border = element_rect(colour = rgb(1.0, 0, 0, 0.5), fill=NA, size=1)
)
The standard plot
 p + mytheme

Removing the strip.text completely
p + mytheme + theme(strip.text = element_blank())

Adding the strip.text and insetting it
p + mytheme +
     theme(strip.text = element_text(size = rel(3.0), vjust = -4.0))

The re-inclusion of strip.text (and the increased relative size) increases the vertical margin between the two rows. So at this point, I don't know how to close the vertical gap between the top and bottom rows.

Too much negative margin
p + mytheme +
    theme(strip.text = element_text(size = rel(3.0), vjust = -4.0), 
          panel.margin = unit(c(-2, -2), "lines"))

So how do I target just the panel.margin between the two rows?

Edit: Additional information. The space between the rows appears to be strip.background:

p + mytheme +
        theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
              panel.margin = unit(-1, "lines"),
              strip.background = element_rect(fill = rgb(0, 1.0, 0, 0.2)))


回答1:


Among the list of possible arguments to theme(), there is not only panel.margin ("margin around facet panels (unit)", see ?theme), but conveniently, you can also access one of the axes at a time, with panel.margin.x and panel.margin.y respectively ("horizontal/vertical margin around facet panels (unit; inherits from panel.margin)").

Therefore, while decreasing the margin below zero feels a bit like a hack, something like the following will do the job (you might have to adjust the value a little - unit(-2, "lines") worked best for me):

p + theme(strip.text = element_text(size = rel(3.0), vjust = -4.0), 
          panel.margin.y = unit(-2, "lines"))

If you use strip.text = element_blank(), then you should probably use panel.margin.y = unit(-0.5, "lines").



来源:https://stackoverflow.com/questions/32426951/in-ggplot2-and-facet-wrap-how-to-remove-all-margins-and-padding-yet-keep-strip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!