Search code examples
rggplot2bar-chartstacked-bar-chart

GGPLOT2: Stacked bar plot for two discrete variable columns


I have a dataset with three columns (one categorical column and two-discrete variables column). I want to make a stacked bar plot to compare the values of the two discrete variables for each category. However, I get continuous coloring rather than discrete colors.

Reproducible code

sampleData <-  data.frame(grp = c("A","B", "C"),
                          var_1 = c(15,20, 25),
                          var_2 = c(12, 13, 20))
sampleData

p <- ggplot(sampleData, aes(x = grp, y = var_1, fill= var_2)) +
  geom_bar( stat="identity", position = "fill")+
  coord_flip()+ theme_bw()
p

Output from above code

Instead, what I want is

Expected output

*Var2 will always be smaller than its corresponding Var1 value for a particular category.

Thanks for the help!


Solution

  • Your problem here is that you haven't fixed your tibble from Wide to Long.

    FixedData <- sampleData %>%
      pivot_longer(cols = c("var_1", "var_2"), names_prefix = "var_", 
                   names_to = "Variable Number", values_to = "ValueName")
    

    Once you do this, the problem becomes much easier to solve. You only need to change a few things, most notably the y, fill, and position variables to make it work.

    p2 <- ggplot(FixedData, aes(x = grp, y = ValueName, fill = `Variable Number`)) +
      geom_bar(stat="identity", position = "stack")+
      coord_flip()+ theme_bw()
    
    p2