Home > OS >  Overlapping Area chart ggplot2 R
Overlapping Area chart ggplot2 R

Time:06-24

seeking help with creating stacked graph in R.

Example data:

Brand <- c('A', 'A', 'C', 'B', 'B', 'C', 'A, 'A', 'C', 'B', 'B', 'C', 'A'') 
Month<- c( 'January', 'January', 'March', 'February', 'April', 'Spetember', 'May', 'July', 'June', 'November', 'December', 'October', 'August')             
Value <- runif(13, 0.0, 30.0)      
data <- data.frame(Brand , Month, Value)

Here is what I was capable of making:

ggplot(data,
                      aes(x = Month,
                          y = Value,
                          group = Brand,
                          fill = Brand))  
        geom_area()  
  expand_limits( x = c(0,NA), y = c(0,NA))  
  scale_y_continuous(labels = scales::comma)  
  guides(fill = guide_legend(title = "Brand"))

enter image description here

And here is desired outcome (made in excel): enter image description here

We would like to see the values of all brand in time, as showed on excel chart. Any ideas how to achieve similar outcome with ggplot in R?

Thanks to any idea in advance

CodePudding user response:

I am not sure whether this is what the question asks for.
geom_area's default position is position="stack", therefore the areas shouldn't be covering other areas drawn first. So, I believe that the problem is with incomplete data, meaning, no data for certain combinations of brand and month. The code below uses tidyr::complete to fill in those values with zeros and then plots the transformed data.

Note: In the posted data, there was a repetition of brand "A" in January. I have changed the 2nd brand to "B".

suppressPackageStartupMessages({
  library(dplyr)
  library(tidyr)
  library(ggplot2)
})
  
set.seed(2022)
Brand <- c('A', 'B', 'C', 'B', 'B', 'C', 'A', 'A', 'C', 'B', 'B', 'C', 'A') 
Month<- c( 'January', 'January', 'March', 'February', 'April', 'September', 
           'May', 'July', 'June', 'November', 'December', 'October', 'August')             
Value <- runif(13, 0.0, 30.0)      
data <- data.frame(Brand , Month, Value)

data %>%
  group_by(Brand) %>%
  complete(Month = month.name, 
           fill = list(Value = 0)) %>%
  mutate(Month = factor(Month, levels = month.name)) %>%
  arrange(Brand, Month) %>%
  ggplot(
    aes(x = Month, y = Value, group = Brand, fill = Brand)
  )  
  geom_area()  
  scale_y_continuous(labels = scales::comma)  
  scale_fill_manual(values = c(A = "#5f7530", B = "#772c2a", C = "#4bacc6"))  
  guides(fill = guide_legend(title = "Brand"))  
  theme_bw()  
  theme(
    axis.text.x = element_text(angle = 45, vjust = 1, hjust=1),
    legend.position = "bottom"
  )

Created on 2022-06-23 by the Plot result with your data

  • Related