我的解决方案基于@user20650提供的答案。不同之处在于使用半自动程序来查找需要用g2
中的元素替换g1
元素的索引。
p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
geom_point() +
facet_grid(vs ~ am)
p2 <- p1 + coord_cartesian(ylim = c(3,4)) +
theme_bw() +
theme(axis.text = element_text(color="blue"),
strip.text = element_text(color="blue"))
p1
p2
现在我们修改顶部行的y轴限制。我们生成两个grobs g1
和g2
,并将g1
中的面板和y轴替换为g2
中对应的元素。
下面的代码根据元素的名称找到要替换的grob元素的索引。
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
panels_to_replace_with_g2 <- c(1,2)
pattern_for_specific_panels <-
paste0("^panel-((",paste0(panels_to_replace_with_g2, collapse = ")|("),"))")
pattern_for_axes_ticks <-
"^GRID.absoluteGrob"
idx_panels_to_replace_from_g2 <- which(unlist(
lapply(g1[["grobs"]], function(x) grepl(pattern_for_specific_panels, x$name))))
idx_axesTicks <- which(unlist(
lapply(g1[["grobs"]], function(x) grepl(pattern_for_axes_ticks, x$name))))
g_test <- g1
for (itr in idx_axesTicks) {
g_test[["grobs"]][[itr]] <- g2[["grobs"]][[itr]]
grid.newpage();grid.draw(g_test); grid.draw(textGrob(itr, just = "top"))
Sys.sleep(1)
}
idx_axesTicks_to_replace <- 10
现在已经找到要替换的面板的索引
idx_panels_to_replace_from_g2
和 y 轴元素的索引
idx_axesTicks_to_replace
。我们可以按照以下方式进行替换。
grid.newpage();grid.draw(g1)
for (iter in idx_panels_to_replace_from_g2) {
g1[["grobs"]][[iter]] <- g2[["grobs"]][[iter]]
grid.newpage();grid.draw(g1)
Sys.sleep(1)
}
g1[["grobs"]][[idx_axesTicks_to_replace]] <- g2[["grobs"]][[idx_axesTicks_to_replace]]
grid.newpage()
grid.draw(g1)
如果成功修改了图表,现在可以删除我们应用于p2的主题修改和文本颜色,以使更改更加明显。
![modified plot](https://istack.dev59.com/xLANA.webp)
未来
TODO
:现在缺少的是增加y轴宽度以尊重修改后的轴标签。
mt + facet_grid(vs ~ am, scales = "free") + coord_cartesian(ylim = c(3,4))
对我来说似乎是有效的,或者我可能没有理解问题。 - mnelfacet_wrap
,这种情况下 x 轴也会被适当地截断mt + facet_wrap(vs ~ am, scales = "free") + coord_cartesian(ylim = c(3,4))
。 - mnel