Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a ribbon plot with variables from different datasets?

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

like image 344
emilk Avatar asked Jan 17 '26 06:01

emilk


1 Answers

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)

like image 183
stefan Avatar answered Jan 19 '26 18:01

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!