Fill area between two lines, with high/low and dates

前端 未结 3 533

Forword: I provide a reasonably satisfactory answer to my own question. I understand this is acceptable practice. Naturally my hope is to invite suggestions and improvements.

3条回答
  •  抹茶落季
    2021-02-03 13:13

    @walts answer should remain the winner but while implementing his solution, I gave it a tidy update.

    library(tidyverse)
    set.seed(2345)
    
    # fake data​
    raw_data <-
      tibble(
        date = as.Date("2020-01-01") + (1:40),
        a = 95 + cumsum(runif(40, min = -20, max = 20)),
        b = 55  + cumsum(runif(40, min = -1, max = 1))
      )
    ​
    # the steps
    # the 'y' + 'min_line'  + 'group' is the right granularity (by date) to 
    # create 2 separate ribbons
    df <-
      raw_data %>% 
      # find min of the two columns
      mutate(min_line = pmin(a, b)) %>% 
      pivot_longer(c(a, b), names_to = "group", values_to = "y") %>% 
      print()
    ​
    # the result
    ggplot(data = df, aes(x = date, fill = group)) +
      geom_ribbon(aes(ymax = y, ymin = min_line)) +
      theme_classic()
    

提交回复
热议问题