【问题标题】:How to display strip labels below the plot when faceting?刻面时如何在图下方显示条形标签?
【发布时间】:2012-04-07 22:17:41
【问题描述】:

似乎条带总是在 ggplot2 创建的图上方。可以将它们移到情节下方吗?

例如:

library(ggplot2) 
qplot(hwy, cty, data = mpg) + facet_grid( . ~ manufacturer)

在顶部显示汽车信息。它们可以显示在底部吗?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

更新:使用ggplot2 2.1.0 版,考虑使用switch = 'x'。详情请见?facet_grid

使用gtable函数,很容易移动条带。 (或查看 here 的另一个版本 - 交换 x 轴和条带)

library(ggplot2)
library(gtable)
library(grid)

p <- ggplot(mpg, aes(hwy, cty)) + geom_point() + facet_grid( . ~ manufacturer) +
     theme(strip.text.x = element_text(angle = 90, vjust = 1),
           strip.background = element_rect(fill = NA))

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the panels in the layout: t = top, l = left, ...
panels <-c(subset(gt$layout, grepl("panel", gt$layout$name), select = t:r))

# Add a row below the x-axis tick mark labels,
# the same height as the strip
gt = gtable_add_rows(gt, gt$height[min(panels$t)-1], max(panels$b) + 2)

# Get the strip grob
stripGrob = gtable_filter(gt, "strip-t")

# Insert the strip grob into the new row
gt = gtable_add_grob(gt, stripGrob, t = max(panels$b) + 3, l = min(panels$l), r = max(panels$r))

# remove the old strip
gt = gt[-(min(panels$t)-1), ]

grid.newpage()
grid.draw(gt)

【讨论】:

  • 如果你和我一样想要条形标签 x 轴上,你可以使用 gt = gtable_add_grob(gt, stripGrob, t = max(panels$b) + 1, l = min(panels$l), r = max(panels$r)) 代替 Sandy 的标签
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
相关资源
最近更新 更多