如何使用ggplot填充geom_line()图下的区域?

时间:2019-12-12 12:22:12

标签: r ggplot2

我试图填充通过ggplot绘制的两条线下方和上方的区域。 这些是绘制的数据点:

polygon_data <- data.frame(checkpoints=c(650,1625,3250,650,1625,3250), lower=c(-1.17,0.20,1.36,-Inf,-Inf,-Inf), upper=c(2.28,1.75,1.36,Inf,Inf,Inf))
checkpoints_data <- data.frame(checkpoints=c(650,1625,3250),design.lower.bound=c(-1.17,0.20,1.36),design.upper.bound=c(2.28,1.75,1.36))


ggplot()+
  geom_polygon(data=polygon_data,mapping=aes(x=checkpoints, y=lower, fill="red", alpha=0.8))+
  geom_polygon(data=polygon_data,mapping=aes(x=checkpoints, y=upper, fill="green", alpha=0.8))+
  geom_line(checkpoints_data,mapping= aes(x=checkpoints, y=design.upper.bound))+
  geom_line(checkpoints_data,mapping= aes(x=checkpoints, y=design.lower.bound))+
  geom_point(checkpoints_data,mapping= aes(x=checkpoints, y=design.lower.bound))+
  geom_point(checkpoints_data,mapping= aes(x=checkpoints, y=design.upper.bound))

这就是我得到的,而不是完全填充两个区域。同样,ggplot不尊重颜色,我也不明白为什么:

绘制图像

enter image description here

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为您在polygon_data数据框中的坐标不正确。 c(650, 1625, 3250, 650, 1625, 3250)应该是c(650, 1625, 3250, 3250, 1625, 650)

尝试一下:

polygon_data <- data.frame(checkpoints = c(650, 1625, 3250, 3250, 1625, 650),
                           lower = c(-1.17, 0.20, 1.36, -Inf, -Inf, -Inf),
                           upper = c(2.28, 1.75, 1.36, Inf, Inf, Inf))

也许将alpha参数放在aes()外面也是个好主意。这样可以避免获得额外的图例。 fill的图例看起来也有些怪异。也许将fill放在aes()外面也是个好主意。