How to make a double cumulative graph in R

70 views Asked by At

enter image description here

How to make this type of graphs in r?

Product Revenue Quantity    Rev Cum Quat Cum
Product A   50% 40% 50% 40%
Product B   25% 30% 75% 70%
Product C   15% 20% 90% 90%
Product D   10% 10% 100%    100%
1

There are 1 answers

2
IceCreamToucan On

geom_rect takes 4 coordinates and makes a rectangle. mutate_at(-1 with funs(...) as a second argument creates new variables for each column except for column 1 with the function specified inside funs. Same for mutate_at(vars(matches('cum')), but in that case new columns are created for only variables whose name contains 'cum'.

library(tidyverse)

df <- read_table("
Product Revenue Quantity    Rev Cum Quat Cum
Product_A   50% 40% 50% 40%
Product_B   25% 30% 75% 70%
Product_C   15% 20% 90% 90%
Product_D   10% 10% 100%    100%
")[1:3]

df %>% 
  mutate_at(-1, funs(cum = cumsum(parse_number(.)))) %>% 
  mutate_at(vars(matches('cum')), funs(lag = lag(., default = 0))) %>% 
  ggplot() +
    geom_rect(aes(xmin = Revenue_cum_lag, 
                  ymin = Quantity_cum_lag, 
                  xmax = Revenue_cum, 
                  ymax = Quantity_cum))

enter image description here