为双序列折线图添加指定置信区间(ggplot报错解决)
问题解决:ggplot绘制带置信区间的折线图报错
问题背景
需要复现目标折线图:
- 蓝色折线对应数据框
fig4的complete_preds_means列 - 橙色折线对应
contrafact列 - 为蓝色折线添加由
complete_preds_lower和complete_preds_upper定义的置信区间
使用以下代码时触发报错:
plot_fig4 <- ggplot()+ geom_line(data=fig4, aes(x=dias, y=complete_preds_means), colour="blue")+ geom_line(data=fig4, aes(x=dias, y=contrafact), colour="red") + geom_ribbon(aes(ymin=fig4$complete_preds_lower, ymax=fig4$complete_preds_upper))+ labs(y="Clase ($)", x="") + scale_y_continuous(breaks=seq(from=100, to=800, by=100))+ scale_x_date(expand = c(0, 0), date_breaks="1 month", date_labels = "%b\n%Y")
报错信息:
Error: geom_ribbon requires the following missing aesthetics: x or y, xmin and xmax
数据结构:
structure(list(dias = structure(c(19052, 19053, 19054, 19055, 19056, 19057, 19058, 19059, 19060, 19061, 19062, 19063, 19064, 19065, 19066, 19067, 19068, 19069, 19070, 19071), class = "Date"), complete_preds_means = c(341.07434, 381.59167, 455.47815, 485.05597, 527.60876, 562.63965, 602.48975, 624.663, 626.5637, 527.2239, 420.71643, 389.30804, 378.74396, 366.61548, 361.36566, 363.37253, 319.31824, 314.39688, 303.60342, 294.8934), contrafact = c(364.5, 358.89, 466.64, 470.11, 464.25, 487.27, 591.2, 715.33, 628.02, 505.98, 402.9, 316.81, 323.35, 358.61, 354.26, 369.5, 317.01, 336.5, 285.33, 270.91), complete_preds_lower = c(320.6368042, 361.7870895, 432.4487762, 461.2275833, 503.2255051, 535.7108551, 576.3850006, 597.9762146, 601.4407013, 504.0448837, 398.7777023, 368.0046799, 356.3603165, 345.5847885, 339.9679932, 342.7514801, 298.3247482, 293.4419693, 282.5286865, 275.4635284), complete_preds_upper = c(359.9897186, 402.5708664, 477.4746765, 508.7775711, 550.3326447, 587.6521027, 628.5320251, 649.9691833, 649.4831665, 547.9886108, 442.046402, 410.8121475, 399.0208908, 389.8615128, 387.4929993, 386.2935928, 340.140834, 336.3622116, 324.793483, 315.4606934)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))
错误原因
geom_ribbon未指定data来源,也未映射x轴变量dias,无法确定置信区间的横向位置- 直接使用
fig4$complete_preds_lower的外部引用方式不符合ggplot语法规范,应在aes()内直接引用列名
修正后的代码
plot_fig4 <- ggplot() + # 先画置信区间,避免遮挡折线 geom_ribbon(data = fig4, aes(x = dias, ymin = complete_preds_lower, ymax = complete_preds_upper), fill = "lightblue", alpha = 0.3) + # 蓝色折线:complete_preds_means geom_line(data = fig4, aes(x = dias, y = complete_preds_means), colour = "blue") + # 橙色折线:contrafact(替换原代码的red为需求的orange) geom_line(data = fig4, aes(x = dias, y = contrafact), colour = "orange") + labs(y = "Clase ($)", x = "") + scale_y_continuous(breaks = seq(from = 100, to = 800, by = 100)) + scale_x_date(expand = c(0, 0), date_breaks = "1 month", date_labels = "%b\n%Y") # 显示图形 plot_fig4
说明
- 将
geom_ribbon放在折线层之前,避免置信区间遮挡折线 - 为置信区间设置浅蓝色填充和低透明度(
alpha=0.3),保证折线清晰可见 - 把
contrafact折线的颜色从red改为需求的orange
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

