用geom_abline遮盖绘图的“超出范围”区域

时间:2020-11-09 15:02:23

标签: r ggplot2 dplyr graphics

我有一个简单的ggplot图,看起来像这样-

ggplot(df, aes(x=n, y=n_e, colour = itt, linetype = itt)) +
  # stat smooth for the lines only (using glm, y ~ x)
  geom_smooth(method = glm, se=F) +
  # tweak defaults a little
  update_geom_defaults("smooth", list(size = 0.7)) + 
  # manually tweak colors/linetype
  scale_colour_manual(values=c("Black","Black")) +
  scale_linetype_manual(values = c("solid","dashed"))+
  geom_abline(intercept = 0, slope = 1, color="red", 
              linetype="dotted", size=0.8)

因为我没有包含任何虚拟数据,所以它是这样的。

红色虚线后面的区域超出范围(即,由于y受x约束,我的数据不能落后于此)。

我想沿着y轴每0.1绘制一系列细的水平线,以阴影该区域。线的斜率为1,所以x1 = y1,x2 = y2等。

如何生成数据以绘制线并将其添加到现有图中。

谢谢 杰米a plot

2 个答案:

答案 0 :(得分:2)

不清楚为什么您没有包括任何虚拟数据。这使得复制剧情变得更加困难。以下是尝试这样做的方法。

library(ggplot2)

df <- data.frame(x = 0, y = c(0, 0, -0.2),
                 xend = c(3, 22, 22), yend = c(3, 3, 2.2),
                 lty = 3:1,
                 col = c("red", "black", "black"))

p <- ggplot(df, aes(x, y, color = col, linetype = lty)) +
  geom_segment(aes(xend = xend, yend = yend)) +
  scale_color_identity() +
  scale_linetype_identity()

p

这实际上是困难的部分。这些行非常简单-只需一个geom_segment调用就足够了:

p + geom_segment(
  data = data.frame(x = 0, y = seq(0, 3, 0.06)),
  aes(xend = y, yend = y), color = "red", size = 0, linetype = 1
)

reprex package(v0.3.0)于2020-11-09创建

答案 1 :(得分:1)

根据艾伦的回答,

我遇到了一些错误,但这是可行的

 + geom_segment(data = data.frame(x = 0, y = seq(0, 3.5, 0.06)),
  aes(x = y, xend = x, y = y, yend = y), color = "red", size = 0.5, linetype = 1, inherit.aes = FALSE)