R图跳跃置信区域

时间:2019-02-27 18:48:50

标签: r ggplot2

我正在尝试创建一个置信带,每年更新一次。

这是我要创建的情节的一个示例: graph from excel

一些可复制的数据如下:

x_axis <- seq(1,24)
confidence_low_yr_1 <- c(seq(40,by=15, length.out = 12),rep(NA,12))
confidence_high_yr_1 <- c(seq(140,by=15, length.out = 12),rep(NA,12))
confidence_low_yr_2 <- c(rep(NA,11),seq(250,by=15, length.out = 13))
confidence_high_yr_2 <- c(rep(NA,11),seq(315,by=15, length.out = 13))

当我尝试绘制线条时,收到关于长度不匹配的错误。我猜想这与NA值有关。我不确定该如何处理,因此将不胜感激。另一个问题是填写行之间的。

这有可能吗?

2 个答案:

答案 0 :(得分:2)

可以通过geom_ribbon()实现。

library(ggplot2)

x_axis <- seq(1,24)
confidence_low_yr_1 <- c(seq(40,by=15, length.out = 12),rep(NA,12))
confidence_high_yr_1 <- c(seq(140,by=15, length.out = 12),rep(NA,12))
confidence_low_yr_2 <- c(rep(NA,11),seq(250,by=15, length.out = 13))
confidence_high_yr_2 <- c(rep(NA,11),seq(315,by=15, length.out = 13))

data = data.frame(x_axis = x_axis,confidence_low_yr_1 = confidence_low_yr_1,confidence_high_yr_1 = confidence_high_yr_1,confidence_low_yr_2 = confidence_low_yr_2,confidence_high_yr_2 = confidence_high_yr_2 )

ggplot(data, aes(x = x_axis))+
  geom_ribbon(aes(ymin = confidence_low_yr_1,ymax = confidence_high_yr_1))+
  geom_ribbon(aes(ymin = confidence_low_yr_2,ymax = confidence_high_yr_2))

答案 1 :(得分:1)

graphics.off()
plot(1,
     xlim = range(x_axis),
     ylim = range(c(confidence_high_yr_1,
                    confidence_high_yr_2,
                    confidence_low_yr_1,
                    confidence_low_yr_2),
                  na.rm = TRUE),
     type = "n")
lines(x_axis, confidence_high_yr_1)
lines(x_axis, confidence_high_yr_2)
lines(x_axis, confidence_low_yr_1)
lines(x_axis, confidence_low_yr_2)

enter image description here