Fill area between multiple lines in plot

前端 未结 1 1998
無奈伤痛
無奈伤痛 2021-01-27 08:17

I have got a plot with 3 lines as follows:

a = data.frame(time = c(1:100), x = rnorm(100))
b = data.frame(time = c(1:100), y = rnorm(100))
c = data.frame(tim         


        
相关标签:
1条回答
  • 2021-01-27 09:01

    Here is an approach:

    a = data.frame(time = c(1:100), x = rnorm(100))
    b = data.frame(time = c(1:100), y = rnorm(100))
    c = data.frame(time = c(1:100), z = rnorm(100))
    

    calculate the pmin and pmax:

    min_a <- pmin(a, b, c)
    max_a <- pmax(a, b, c)
    

    construct the polygon as usual:

    polygon(c(c$time, rev(c$time)), c(max_a$x ,rev(min_a$x)), col = rgb(1, 0, 0,0.5) )
    

    or using ggplot:

    library(tidyverse)
    data.frame(a, b, c) %>% #combine the three data frames
      group_by(time) %>% # group by time for next step
      mutate(max = max(x, y, z), # calculate max of x, y, z in each time
             min = min(x, y, z)) %>% #same as above
      select(-time.1, - time.2) %>% #discard redundant columns
      gather(key, value, 2:4) %>% #convert to long format so you can color by key in the geom line call
      ggplot()+
      geom_ribbon(aes(x = time, ymin= min, ymax = max), fill= "red", alpha = 0.3)+
      geom_line(aes(x = time, y = value, color = key))
    

    0 讨论(0)
提交回复
热议问题