Search code examples
rggplot2geom-area

Stacked ggplot2 geom_area reruns an empty graph


I am trying to us geom_area to produce a stacked area graph but it producing an entry graph. Here is an example

library(dplyr)
library(ggplot2)

x = expand.grid(name = c("D01", "D02", "D03", "D04"), component = c("F", "W", "M", "V"))
value = runif( min = 20, max = 150, nrow(x))

data2 = cbind(x, value) %>%
  dplyr::arrange(name)

ggplot2::ggplot(data = data2, aes(x = name, fill = factor(component))) + 
                  ggplot2::geom_area(aes(y = value), position = 'stack') 

I read the questions Why is my stacked area graph in ggplot2 empty and Why is my stacked area graph in ggplot2 empty but the solutions posted there they did not resolve my problem. Thanks for any suggestions.


Solution

  • If we convert the 'x' factor to integer, it should work

    library(ggplot2)
    library(dplyr)
    data2 %>% 
         mutate(name = as.integer(name)) %>%
         ggplot(aes(x = name, fill = component)) +
             geom_area(aes(y = value), position = 'stack')+
             scale_x_continuous(labels = levels(data2$name))
    

    enter image description here