小平面板中的下降器侵入面板背景

时间:2015-07-09 00:35:15

标签: r ggplot2

我在白色背景上有一个带有灰色小平面和白色小平面文字的情节:

ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
       aes(x = x, y = y, color = color)) + 
  geom_point() + 
  facet_grid(~color) + 
  theme(panel.background = element_blank(), 
        strip.text = element_text(color = "white", size = 23)) 

enter image description here

我的问题是下降器(p,g,q,j)越过了这个方面。我希望条带背景在文本周围有一个边距,以便构面文本中的所有字形始终严格在构面矩形内。我可以在构面文本color = c("Ap\n", "Ap\n", "B\n", "B\n")中添加换行符,但边距过大(或者所需的lineheight太难看了)。是否有ggplot2解决方案?

1 个答案:

答案 0 :(得分:5)

对于ggplot v2.2.0 theme中,请在strip_text元素中指定边距(请参阅here

# Set text size
size = 26

library(ggplot2)
library(grid)

p = ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
      aes(x = x, y = y, color = color)) + 
      geom_point() + 
      facet_grid(~color) + theme_bw() +
      theme(strip.text = element_text(color = "white", size = size)) 


  p +
  theme(strip.text.x = element_text(margin = margin(.1, 0, .3, 0, "cm")))

<强>原始 您可以使用ggplot布局来调整条带的高度。高度可以设置为绝对高度,例如unit(1, "cm"),或者,就像我在这里所做的那样,设置为调整为字体大小的高度。

编辑:更新到ggplot2 2.0.0
进一步修改:不再需要更新到网格3.0.0 grid:::unit.list()

# Set text size
size = 26

library(ggplot2)
library(grid)

p = ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
      aes(x = x, y = y, color = color)) + 
      geom_point() + 
      facet_grid(~color) + theme_bw() +
      theme(strip.text = element_text(color = "white", size = size)) 


# Get ggplot grob
g <- ggplotGrob(p)

# Set the relevant height
g$heights[3] = unit(2, "grobheight", textGrob("a", gp=gpar(fontsize = size))) 


grid.newpage()
grid.draw(g)

enter image description here