Home > Blockchain >  Mixing stacked and unstacked bars in single graph
Mixing stacked and unstacked bars in single graph

Time:12-13

I'm trying to mix stacked and unstacked bars in one graph.

Here is sample code:

Indicators <- c("Childhood Physical Abuse","Childhood Neglect","Childhood Sexual Abuse Severity",
                "No CSA","Non-contact childhood sexual abuse","Low-risk contact childhood sexual abuse",
                "High-risk contact childhood sexual abuse","Adulthood Sexual Assault","Sexual Intimate Partner Violence",
                "Adulthood Physical Assault","Physical Intimate Partner Violence","Discrimination","Low discrimination",
                "Medium discrimination","High discrimination","Stigma Consciousness","Low stigma consciousness","Medium stigma consciousness",
                "High stigma consciousness","Internalized Stigma","Low internalized stigma","Medium internalized stigma",
                "High internalized stigma")

Class_1 <- c(0.44,0.01,"",0.6,0.13,0.11,0.16,0.08,0.01,0.14,0.21,"",0.55,
0.23,0.22,"",0.4,0.31,0.29,"",0.41,0.23,0.36)

data <- data.frame(Indicators,Class_1)

The table would look like: enter image description here

As you can see, some variables need to be stacked while others don't.

How can I make a graph with both unstacked and stacked bars? I really appreciate all the help there is! Thanks!

CodePudding user response:

Basically you want a stacked barchart even if for some categories there is nothing to stack. To this end you have to do some data wrangling and cleaning like getting rid of the empty value rows and splitting the Indicators column in two:

library(dplyr)
library(ggplot2)
library(tidyr)

data1 <- data |> 
  filter(Class_1 != "") |> 
  mutate(Class_1 = as.numeric(Class_1)) |> 
  separate(Indicators, into = c("level", "which"), fill = "left") |> 
  replace_na(list(level = "Total"))

ggplot(data1, aes(which, Class_1, fill = level))  
  geom_col()

enter image description here

CodePudding user response:

Update: (@camille is right. I now adapted my answer and removed the first one)

library(tidyverse)
data %>% 
  separate(Indicators, c("Indicators_1",  "Indicators_2")) %>% 
  mutate(Indicators_3 = ifelse(is.na(Indicators_2), "Total", Indicators_1),
         Indicators_2 = coalesce(Indicators_2, Indicators_1)) %>% 
  filter(Class_1 != "") %>% 
  ggplot(aes(x = Indicators_2, y = as.numeric(Class_1), fill= Indicators_3)) 
  geom_bar(stat = "identity", position = "stack")

enter image description here

  • Related