带有置信带和标签数据点的r线图

问题描述 投票:0回答:1

我试图用置信区间带绘制线图并标记这些数据点。

这是我的数据集

    x        y        lower     upper
 1991-1995   0.0000   0.00000   0.0000
 1996-2000   1.4920  -0.19782   3.1818
 2001-2005   3.2162   0.97042   5.4620
 2006-2010   7.7719   4.66051  10.8833

这是我到目前为止所尝试的

ggplot(df, aes(x, y))+
                  geom_point(color='#E69F00')+
                  geom_line(data=df)+theme_minimal() + 
                  geom_text(aes(label=round(y,4)), vjust=-.5) +
                  geom_ribbon(data=df,aes(ymin= lower,ymax= upper), linetype=2,alpha=0.3)

我一直在收到错误

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

我也没有看到任何CI乐队

任何关于如何解决这个问题的建议都非常感谢。提前致谢。

r ggplot2 confidence-interval
1个回答
1
投票

更好的方法是将x转换为数字变量,以便可以正确排列x轴。 tidyr::separate_rows可以将开始日期和结束日期分隔到不同的行,这样您就可以将它们全部绘制为一行:

library(tidyverse)

df <- data_frame(x = c("1991-1995", "1996-2000", "2001-2005", "2006-2010"), 
                 y = c(0, 1.492, 3.2162, 7.7719), 
                 lower = c(0, -0.19782, 0.97042, 4.66051), 
                 upper = c(0, 3.1818, 5.462, 10.8833))

df %>% 
    separate_rows(x, convert = TRUE) %>% 
    ggplot(aes(x, y, ymin = lower, ymax = upper, label = round(y, 2)[c(TRUE, NA)])) + 
    geom_ribbon(alpha = 0.3) + 
    geom_line() + 
    geom_point() + 
    geom_text(nudge_y = .4)

从这一点来说,如果你愿意,你可以调整很多。

© www.soinside.com 2019 - 2024. All rights reserved.