是否有更好的方法将所有这些段添加到ggplot中,而不是每行都有一个?
annotate("segment", x = -250, xend = -250, y = -50, yend = 315, colour = "gray50") +
annotate("segment", x = 250, xend = 250, y = -50, yend = 315, colour = "gray50") +
annotate("segment", x = -250, xend = 250, y = -50, yend = -50, colour = "gray50") +
annotate("segment", x = -211, xend = -211, y = -50, yend = 110, colour = "gray50") +
annotate("segment", x = 211, xend = 211, y = -50, yend = 110, colour = "gray50") +
annotate("segment", x = -30, xend = 30, y = -10, yend = -10, colour = "gray50") +
annotate("segment", x = -80, xend = -80, y = -50, yend = 140, colour = "gray50") +
annotate("segment", x = -60, xend = -60, y = -50, yend = 140, colour = "gray50") +
annotate("segment", x = 60, xend = 60, y = -50, yend = 140, colour = "gray50") +
annotate("segment", x = 80, xend = 80, y = -50, yend = 140, colour = "gray50") +
annotate("segment", x = -80, xend = 80, y = 140, yend = 140, colour = "gray50") +
annotate("segment", x = 0, xend = 0, y = -10, yend = -5, colour = "gray50")
答案 0 :(得分:3)
您可以为annotate
提供矢量,例如,为您的前三点(我很懒,不能全部输入)
annotate("segment", x = c(-250, 250, -250),
xend = c(-250, 250, 250),
y = c(-50, -50, -50),
yend = c(315, 315, -50),
color = "gray50")
或者,如果您的数据在数据框中,则使用geom_segment
层(根据需要扩展到所有点):
annotation_data = data.frame(x1 = c(-250, 250, -250),
x2 = c(-250, 250, 250),
y1 = c(-50, -50, -50),
y2 = c(315, 315, -50))
geom_segment(data = annotation_data,
mapping = aes(x = x1, xend = x2, y = y1, yend = y2),
color = "gray50)
答案 1 :(得分:0)
将绘图存储在变量中:
library(ggplot2)
data(diamonds)
chart <- ggplot(diamonds, aes(x=depth, y=price)) +
geom_point(alpha=0.1)
将x,xend,y和yend属性存储在可以像列表一样循环的地方:
segment_coords <- list(
c("x"=250, "xend"=-250, "y"=-50, "yend"=315),
c("x"=250, "xend"=250, "y"=-50, "yend"=315)
)
现在,您可以在for循环中创建细分并将其添加到图表中,如下所示:
for (segment in segment_coords) {
chart <- chart + annotate(
"segment",
x = segment["x"],
xend = segment["xend"],
y = segment["y"],
yend = segment["yend"],
colour = "gray50"
)
}
chart