繁体   English   中英

Plot 置信区间 ggplot2

[英]Plot the confidence band with ggplot2

我有一个与此类似的数据集:

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)

我想 plot 整个时间范围内的置信区间,有 2 个不同的组(A 和 B)。

目前我正在使用这种方法,但没有奏效:

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")

在此处输入图像描述

我不确定如何处理这个问题。

你快到了。 只需要对aes()进行一些小的更正。

但首先我会稍微修改输入以使结果看起来更漂亮(现在ci_upper / ci_lower与相应的平均值相比并不总是更多/更少):

# 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))

ggplot()调用中应该更改的主要内容是将用于绘图的美学定义。 请注意,默认美学值只能设置一次。

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"))

结果如下:

plot_res

实际上,最后两行代码甚至都不是必需的,因为默认的 ggplot-color 方案(用于显示所需结果)看起来也非常好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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