【发布时间】:2020-01-03 21:42:40
【问题描述】:
我需要在 ggplot 中重现 InDesign 中生成的绘图以实现重现性。
在这个特定的示例中,我将两个图组合成一个复合图(为此我使用了包 {patchwork})。
然后我需要将连接一个绘图上的关键点的线与底部绘图上的相应点重叠。
这两个图是从相同的数据生成的,具有相同的 x 轴值,但不同的 y 轴值。
我在 Stack Overflow 上看到了这些示例,但这些示例涉及跨方面绘制线条,这在此处不起作用,因为我试图在单独的图中绘制线条:
我尝试了几种方法,到目前为止我最接近的是:
- 使用
{grid}包添加带有 grobs 的行 - 使用
{gtable}将第二个绘图转换为 gtable,并将面板的剪辑设置为关闭,以便我可以将线条向上延伸到绘图面板之外。 - 使用
{patchwork}再次将这些图组合成一个图像。
问题出现在最后一步,因为 x 轴现在不再像添加线并将剪辑设置为关闭之前那样排列(参见代码中的示例)。
我还尝试将这些图与ggarrange、{cowplot} 和{egg} 和{patchwork} 最接近。
以下是我对可以创建的最佳最小代表的尝试,但仍然捕捉到我想要实现的细微差别。
library(ggplot2)
library(dplyr)
library(tidyr)
library(patchwork)
library(gtable)
library(grid)
# DATA
x <- 1:20
data <- data.frame(
quantity = x,
curve1 = 10 + 50*exp(-0.2 * x),
curve2 = 5 + 50*exp(-0.5 * x),
profit = c(seq(10, 100, by = 10),
seq(120, -240, by = -40))
)
data_long <- data %>%
gather(key = "variable", value = "value", -quantity)
# POINTS AND LINES
POINTS <- data.frame(
label = c("B", "C"),
quantity = c(5, 10),
value = c(28.39397, 16.76676),
profit = c(50, 100)
)
GROB <- linesGrob()
# Set maximum y-value to extend lines to outside of plot area
GROB_MAX <- 200
# BASE PLOTS
# Plot 1
p1 <- data_long %>%
filter(variable != "profit") %>%
ggplot(aes(x = quantity, y = value)) +
geom_line(aes(color = variable)) +
labs(x = "") +
coord_cartesian(xlim = c(0, 20), ylim = c(0, 30), expand = FALSE) +
theme(legend.justification = "top")
p1
# Plot 2
p2 <- data_long %>%
filter(variable == "profit") %>%
ggplot(aes(x = quantity, y = value)) +
geom_line(color = "darkgreen") +
coord_cartesian(xlim = c(0, 20), ylim = c(-100, 120), expand = FALSE) +
theme(legend.position = "none")
p2
# PANEL A
panel_A <- p1 + p2 + plot_layout(ncol = 1)
panel_A
# PANEL B
# ATTEMPT - adding grobs to plot 1 that end at x-axis of p1
p1 <- p1 +
annotation_custom(GROB,
xmin = 0,
xmax = POINTS$quantity[POINTS$label == "B"],
ymin = POINTS$value[POINTS$label == "B"],
ymax = POINTS$value[POINTS$label == "B"]) +
annotation_custom(GROB,
xmin = POINTS$quantity[POINTS$label == "B"],
xmax = POINTS$quantity[POINTS$label == "B"],
ymin = 0,
ymax = POINTS$value[POINTS$label == "B"]) +
geom_point(data = POINTS %>% filter(label == "B"), size = 1)
# ATTEMPT - adding grobs to plot 2 that extend up to meet plot 1
p2 <- p2 + annotation_custom(GROB,
xmin = POINTS$quantity[POINTS$label == "B"],
xmax = POINTS$quantity[POINTS$label == "B"],
ymin = POINTS$profit[POINTS$label == "B"],
ymax = GROB_MAX)
# Create gtable from ggplot
g2 <- ggplotGrob(p2)
# Turn clip off for panel so that line can extend above
g2$layout$clip[g2$layout$name == "panel"] <- "off"
panel_B <- p1 + g2 + plot_layout(ncol = 1)
panel_B
# Problems:
# 1. Note the shift in axes when turning the clip off so now they do not line up anymore.
# 2. Turning the clip off mean plot 2 extends below the axis. Tried experimenting with various clips.
期望 panel_B 中的图仍应像 panel_A 中一样显示,但有连接线连接图之间的点。
我正在寻求解决上述问题的帮助,或者尝试其他替代方法。
作为不运行上述代码的参考 - 我无法发布图片链接。
面板 A
面板 B:目前的样子
面板 B:我想要它的样子!
【问题讨论】: