这是你想要的吗?诀窍是ggplot
了解它需要长格式的数据。这通常意味着我们必须在准备绘图之前转换数据,通常使用melt()
.
读取数据后textConnection()
并创建一个名为的对象dat
,以下是您需要采取的步骤:
#Melt into long format
dat.m <- melt(dat, id.vars = "time")
#Not necessary, but if you want different line types depending on quantile, here's how I'd do it
dat.m <- within(dat.m
, lty <- ifelse(variable == "quantile.0.5", 1
, ifelse(variable %in% c("quantile.0.25", "quantile.0.75"),2,3)
)
)
#plot it
ggplot(dat.m, aes(time, value, group = variable, colour = variable, linetype = lty)) +
geom_line() +
scale_colour_manual(name = "", values = c("red", "blue", "black", "blue", "red"))
给你:
再次阅读您的问题后,也许您想要中值估计之外的阴影丝带而不是线条?如果是这样,请尝试一下。这里唯一真正的技巧是我们通过group = 1
作为一种美学,以便geom_line()
将正确处理因子/字符数据。之前,我们按具有相同效果的变量进行分组。另请注意,我们不再使用melt
ed data.frame,因为在这种情况下,宽 data.frame 非常适合我们。
ggplot(dat, aes(x = time, group = 1)) +
geom_ribbon(aes(ymin = quantile.0.05, ymax = quantile.0.95, fill = "05%-95%"), alpha = .25) +
geom_ribbon(aes(ymin = quantile.0.25, ymax = quantile.0.75, fill = "25%-75%"), alpha = .25) +
geom_line(aes(y = quantile.0.5)) +
scale_fill_manual(name = "", values = c("25%-75%" = "red", "05%-95%" = "blue"))
编辑:强制预测值的图例
我们可以使用与之前使用的方法相同的方法geom_ribbon()
层。我们将添加一种美感geom_line()
然后设置该美学的值scale_colour_manual()
:
ggplot(dat, aes(x = time, group = 1)) +
geom_ribbon(aes(ymin = quantile.0.05, ymax = quantile.0.95, fill = "05%-95%"), alpha = .25) +
geom_ribbon(aes(ymin = quantile.0.25, ymax = quantile.0.75, fill = "25%-75%"), alpha = .25) +
geom_line(aes(y = quantile.0.5, colour = "Predicted")) +
scale_fill_manual(name = "", values = c("25%-75%" = "red", "05%-95%" = "blue")) +
scale_colour_manual(name = "", values = c("Predicted" = "black"))
可能有更有效的方法可以做到这一点,但这就是我一直使用的方法,并且取得了相当大的成功。 YMMV。