简体   繁体   中英

Plot the confidence band with ggplot2

I have a dataset that is similar to this:

x <- data.frame(date = c(20190902, 20190903, 20190904),
            Group = c(rep("A", 3)),
            mean = c(2.5, 3.4, 4.6),
            ci_upper = c(1.2, 0.5, 0.3),
            ci_lower = c(0.5, 0.4, 0.25))

y <- data.frame(date= c(20190902, 20190903, 20190904),
            Group = c(rep("B", 3)),
            mean = c(0.4, 3.8, 6.2),
            ci_upper = c(1.9, 0.9, 0.5),
            ci_lower = c(0.5, 0.8, 0.8))

df <- rbind(x, y)

I would like to plot the confidence band across the timeframe, with 2 different groups (A and B).

Currently I'm using this method but didn't work:

p <- ggplot(df) + 
    geom_line(aes(y = mean, x = date, group = type ))+
    geom_ribbon(aes(ymin = ci_lower, ymax = ci_upper, x = week, fill = "grey70"), alpha = 0.3)+
    scale_colour_manual("", values = "blue")+
    scale_fill_manual("", values = "grey12")

在此处输入图像描述

I wasn't sure how I can approach this.

You are almost there. Only some small corrections of the aes() are needed.

But first I would slightly modify the input just to make the result looking prettier (now the ci_upper / ci_lower are not always more/less as compared with a corresponding mean value):

# to ensure reproducibility of the samples
set.seed(123)
df$ci_lower <- df$mean - sample(nrow(x))
df$ci_upper <- df$mean + sample(nrow(x))

The main thing which should be changed in your ggplot() call is definition of the aesthetics which will be used for plotting. Note, please, that default aesthetics values should be set only once.

p <- ggplot(df, 
    aes(x = as.Date(as.character(date), format = "%Y%m%d"), 
        y = mean,
        group = Group, col = Group, fill = Group)) + 
    geom_line() +
    geom_ribbon(aes(ymin = ci_lower, ymax = ci_upper), alpha = 0.3)+
    scale_colour_manual("", values = c("red", "blue")) +
    scale_fill_manual("", values = c("red", "blue"))

The result is as follows:

plot_res

Actually, the last two code rows are even not necessary, as the default ggplot-color scheme (which you have used to show the desired result) looks very nice, also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM