r语言 - 绘制标准偏差



我想在具有线或smoth区域的图中绘制1条线(1个流系列,该图将有2个(的标准差。我已经看到并应用了来自 sd 表示和其他示例的一些代码......但它对我不起作用。

我的原始数据在同一天有几个流量值,我已经计算了其中的每日平均值和 sd。我被困在这里,不知道是否可以用创建的"称为 sd"列中的行来表示每日 sd,或者我应该使用原始数据。

下面的代码是我将应用于数据的一般示例。流量 flow1 和 sd 是原始数据的每日平均值和 sd 结果计算的示例。

library(gridExtra)
library(ggplot2)
library(grid)
x <- data.frame(
date = seq(as.Date("2012-01-01"),as.Date("2012-12-31"), by="week"), 
rain = sample(0:20,53,replace=T),
flow1 = sample(50:150,53,replace=T),
flow = sample(50:200,53,replace=T),
sd = sample (0:10,53, replace=T))

g.top <- ggplot(x, aes(x = date, y = rain, ymin=0, ymax=rain)) +
geom_linerange() +
scale_y_continuous(limits=c(22,0),expand=c(0,0), trans="reverse")+
theme_classic() +
theme(plot.margin = unit(c(5,5,-32,6),units="points"),
axis.title.y = element_text(vjust = 0.3))+
labs(y = "Rain (mm)")
g.bottom <- ggplot(x, aes(x = date)) +
geom_line(aes(y = flow, colour = "flow")) + 
geom_line(aes(y = flow1, colour = "flow1")) + 
stat_summary(geom="ribbon", fun.ymin="min", fun.ymax="max", aes(fill=sd), alpha=0.3) +
theme_classic() +
theme(plot.margin = unit(c(0,5,1,1),units="points"),legend.position="bottom") +
labs(x = "Date", y = "River flow (m/s)") 

grid.arrange(g.top, g.bottom , heights = c(1/5, 4/5))

上面的代码给出了错误:stat_summary需要以下缺失的美学:y

另一种选择是geom_smooth,但据我所知,它需要一些线方程(我可能是错的,我是 R 的新手(。

也许是这样的事情?

g.bottom <- x %>% 
select(date, flow1, flow, sd) %>% 
gather(key, value, c(flow, flow1)) %>%
mutate(min = value - sd, max = value + sd) %>%
ggplot(aes(x = date)) +
geom_ribbon(aes(ymin = min, ymax = max, fill = key)) +
geom_line(aes(y = value, colour = key)) +
scale_fill_manual(values = c("grey", "grey")) +
theme_classic() +
theme(plot.margin = unit(c(0,5,1,1),units="points"),legend.position="bottom") +
labs(x = "Date", y = "River flow (m/s)") 

最新更新