3

I have been plotting from multiple data.frames;

ggplot() +
     geom_line(data=posterior.m, aes(x=time,y=NO.y)) + 
     geom_line(data=posterior.05, aes(x=time,y=NO.y), linetype = "dotted") +
     geom_line(data=posterior.95, aes(x=time,y=NO.y), linetype = "dotted")

Basically, posterior.m cointains medians of the 90 % confidence interval. low 05 is in data frame posterior.05 and high 95 is in posterior.95. In short, this is a plot with 3 lines.

The question is, how can I use geom_ribbon() or something similar by filling between the median and lower and median and upper. Or simply just fill between lower and upper. I can't get this to work as they are not a part of the same data frame.

Thanks

stefan
  • 90,330
  • 6
  • 25
  • 51
emilk
  • 75
  • 5

1 Answers1

2

Using mtcars as example dataset this can be achieved like so:

In your case you have to join by time and probably rename your vars.

library(dplyr)
library(ggplot2)

mtcars1 <- mtcars %>% 
  group_by(cyl) %>% 
  summarise(y_med = median(mpg))
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars2 <- mtcars %>% 
  group_by(cyl) %>% 
  summarise(y_05 = quantile(mpg, probs = .05))
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars3 <- mtcars %>% 
  group_by(cyl) %>% 
  summarise(y_95 = quantile(mpg, probs = .95))
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars_join <- left_join(mtcars1, mtcars2, by = "cyl") %>% 
  left_join(mtcars3, by = "cyl")

ggplot(mtcars_join, aes(cyl)) +
  geom_ribbon(aes(ymin = y_med, ymax = y_95), fill = "red") +
  geom_ribbon(aes(ymin = y_05, ymax = y_med), fill = "blue") +
  geom_line(aes(y = y_med)) +
  geom_line(aes(y = y_05), linetype = "dotted") +
  geom_line(aes(y = y_95), linetype = "dotted")

Created on 2020-06-14 by the reprex package (v0.3.0)

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Thanks! Worked perfectly with "join by time" and renaming – emilk Jun 14 '20 at 13:50
  • My pleasure. If you want to do me a favor. Mark the question as answered and upvote it. Besides giving me some credit it remeoves the question from the queue of questions waiting for answer and shows others with a similiar problem that the solution worked. – stefan Jun 14 '20 at 13:58
  • Consider full_join() instead of left_join() as you may be loosing observations when dealing with other datasets – underscore Jan 15 '22 at 12:46