bison2178
bison2178

Reputation: 789

r line plot with confidence bands and label datapoints

I am trying to draw a lineplot with confidence interval bands and label these datapoints.

This is my dataset below

    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

This is what I have tried so far

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)

I keep getting an error

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

Also I dont see any CI bands

Any suggestions on how to solve this problem is much appreciated. Thanks in advance.

Upvotes: 0

Views: 705

Answers (1)

alistaire
alistaire

Reputation: 43364

A better approach is to convert x to a numeric variable so the x-axis can be arranged properly. tidyr::separate_rows can separate the start and end dates to different rows, which lets you plot it all as one line:

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)

From this point you can tweak a lot, should you like.

Upvotes: 2

Related Questions