0

I want to plot the standard deviation for 1 line (1 flow serie, the plot will have 2) in a plot with lines or smoth areas. I've seen and applied some code from sd representation and other examples... but it's not working for me.

My original data has several flow values for the same day, of which I've calculated the daily mean and sd. I'm stuck here, don't know if it is possible to represent the daily sd with lines from the column created "called sd" or should I use the original data.

The bellow code is a general example of what I'll apply to my data. The flow, flow1 and sd, are examples of the result calculation of daily mean and sd of the original data.

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

The above code gives Error: stat_summary requires the following missing aesthetics: y

Other option is geom_smooth, but as far as I could understand it requires some line equation (I can be wrong, I'm new in R).

Sofy
  • 29
  • 5
  • I could add some column with mean+sd and other with mean-sd and represent. I'll do that as a last resort. – Sofy Jun 12 '18 at 15:35

1 Answers1

0

Something like this maybe?

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)") 
kluu
  • 2,848
  • 3
  • 15
  • 35
  • Yes, something like that, I just altered little because I just want for one flow line. Thank you so much. – Sofy Jun 12 '18 at 18:10