我提出的解决方案基于@user20650提供的答案。它的不同之处在于使用半自动过程来查找 grobg1
中需要替换为g2
.
# library(ggplot2)
# library(grid)
p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
geom_point() +
facet_grid(vs ~ am)
# modify p1 by zooming as desired
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
替换面板和 y 轴。g1
g2
下面的代码根据元素的名称查找要替换的 grob 元素的索引。
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
# Replace the upper panels and upper axis of p1 with that of p2
# i.e. replace the corresponding grobs in g1 with the versions of g2
# Panel numbering goes row-wise from top left to bottom right
panels_to_replace_with_g2 <- c(1,2)
# To get names of grobs run: lapply(g1[["grobs"]],function(x) x$name)
# Use names of grobs to find out indices of g1[["grobs"]] of the panels we want to replace
# as well as for the axis ticks.
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_panels_to_replace_from_g2
# [1] 2 4
idx_axesTicks <- which(unlist(
lapply(g1[["grobs"]], function(x) grepl(pattern_for_axes_ticks, x$name))))
# Find out manually which of the defined axesTicks it is:
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)
}
# We found out it is itr=10
idx_axesTicks_to_replace <- 10
现在已经找到要替换的面板idx_panels_to_replace_from_g2
的索引以及 y 轴元素的索引idx_axesTicks_to_replace
。我们可以在下面替换它们。
# Replace panels
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)
}
# Replace y-axis
g1[["grobs"]][[idx_axesTicks_to_replace]] <- g2[["grobs"]][[idx_axesTicks_to_replace]]
# Render plot
grid.newpage()
grid.draw(g1)
如果绘图成功修改,您现在可以删除我们应用于 p2 的主题修改和文本颜色,以使更改更好地可见。
未来TODO
:现在缺少的是增加y轴的宽度以尊重修改后的轴标签