使用 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)
我想绘制整个时间范围内的置信带,有 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
与相应的平均值相比并不总是 more/less) :
# 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"))
结果如下:
实际上,最后两行代码甚至不是必需的,因为默认的 ggplot-color 方案(您用来显示所需结果的方案)看起来也非常好。
我有一个与此类似的数据集:
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)
我想绘制整个时间范围内的置信带,有 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
与相应的平均值相比并不总是 more/less) :
# 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"))
结果如下:
实际上,最后两行代码甚至不是必需的,因为默认的 ggplot-color 方案(您用来显示所需结果的方案)看起来也非常好。