使用ggplot2时,我想制作一个多面图,其中带状文本位于每个子图及其y轴文本的中心,而不是仅位于子图的中心。作为参考,这是我要创建的绘图的示例:
所需图
r - 使ggplot的条形文字延伸到轴文字上-LMLPHP
这与同一图相反,但是 strip 文本仅在子图区域上居中,如下所示。
默认ggplot2图
r - 使ggplot的条形文字延伸到轴文字上-LMLPHP
作为参考,以下是用于生成该图的代码:

library(ggplot2)
library(dplyr)

diamonds_plot <- diamonds %>%
  filter(clarity %in% c("IF", "I1")) %>%
  ggplot(aes(x = price, y = cut)) +
  geom_point() +
  facet_wrap(~ clarity, scales = 'free')
如何以编程方式进行此更改?
我猜想这可以通过编辑从调用diamonds_plot %>% ggplot_build %>% ggplot_gtable()获得的布局对象来完成,但是很难确定确切的更改。

最佳答案

是的,您有正确的想法。

g <- ggplotGrob(diamonds_plot)
g$layout
#     t  l  b  r  z clip        name
# 20  1  1 11 11  0   on  background
# 1   7  4  7  4  1   on   panel-1-1
# 2   7  8  7  8  1   on   panel-2-1
# 3   5  4  5  4  3  off  axis-t-1-1
# 4   5  8  5  8  3  off  axis-t-2-1
# 5   8  4  8  4  3  off  axis-b-1-1
# 6   8  8  8  8  3  off  axis-b-2-1
# 7   7  7  7  7  3  off  axis-l-1-2
# 8   7  3  7  3  3  off  axis-l-1-1
# 9   7  9  7  9  3  off  axis-r-1-2
# 10  7  5  7  5  3  off  axis-r-1-1
# 11  6  4  6  4  2   on strip-t-1-1
# 12  6  8  6  8  2   on strip-t-2-1
# 13  4  4  4  8  4  off      xlab-t
# 14  9  4  9  8  5  off      xlab-b
# 15  7  2  7  2  6  off      ylab-l
# 16  7 10  7 10  7  off      ylab-r
# 17  3  4  3  8  8  off    subtitle
# 18  2  4  2  8  9  off       title
# 19 10  4 10  8 10  off     caption

移位 strip 的左边缘:
g$layout$l[g$layout$name == "strip-t-1-1"] <- 3
g$layout$l[g$layout$name == "strip-t-2-1"] <- 7
# or more programmatically, with thanks to Mike H.
# g$layout$l[grepl("strip-t", gp$layout$name)] <- g$layout$l[grepl("strip-t", gp$layout$name)] - 1
grid::grid.draw(g)

输出:
r - 使ggplot的条形文字延伸到轴文字上-LMLPHP

关于r - 使ggplot的条形文字延伸到轴文字上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50180450/

10-12 16:49
查看更多