首页 > 解决方案 > R图跳跃置信区域

问题描述

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

这是我正在尝试创建的情节示例: 来自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 值有关。我不知道该怎么做,所以任何帮助将不胜感激。另一个问题是填补字里行间的空白。

这甚至可能吗?

标签: rggplot2

解决方案


可以用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))

推荐阅读