Home > Back-end >  Mixed Variable Stacked Barplot
Mixed Variable Stacked Barplot

Time:12-16

I would like to produce a GGPlot stacked barplot with variables on the horizontal axis, yet some variables have different responses.

Some variables are 'Y/N' responses. Some variables are 'Old/Young'. And some of the variables are a Likert scale of 0-5.

Therefore, I would like to plot these in a stacked barplot form, with each variable type encoded with a different colour palette, and with a legend reflecting the different palettes/variable types.

I wondered if someone could help with this, please? Would be greatly appreciated.

X1<-c("N","N","N","N","Y","N","Y","N","N","N","N","N","Y","N","N","Y","N","N","N","Y","N","Y","Y","N","N","Y","Y","Y","N","N","N","N","N","N","N","N","Y","N","Y","N","N","N","N","Y","N","N","Y","N","Y","Y","N","Y","N","N")
X2 <-c("N","N","N","N","Y","N","Y","N","N","N","N","N","Y","N","N","Y","N","N","N","Y","N","Y","Y","N","N","Y","Y","Y","N","N","N","N","N","N","N","N","Y","N","Y","N","N","N","N","Y","N","N","Y","N","Y","Y","N","Y","N","N")
X3<-c(1,1,0,1,2,0,0,0,0,0,1,1,1,2,0,1,2,1,1,0,0,0,4,1,0,0,0,0,1,0,2,0,0,2,1,1,0,0,0,1,1,0,1,0,1,0,1,1,0,1,0,1,1,1)
X4 <-c("YouNg","Old","Old","YouNg","Old","Old","Old","YouNg","YouNg","YouNg","Old","Old","Old",
       "Old","Old","Old","Old","YouNg","Old","Old","Old","YouNg","YouNg","Old","Old","Old",
       "Old","Old","Old","Old","Old","Old","Old","YouNg","Old","YouNg","Old","YouNg","Old",
       "Old","YouNg","Old","YouNg","YouNg","Old","Old","Old","YouNg","Old","Old","Old","YouNg", "Old", "Old")

Y <- data.frame(X1, X2, X3, X4)

CodePudding user response:

One option to achieve your desired result would to use the ggnewscale package which allows for multiple scales and legends for the same aesthetic:

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

dat <- Y |> 
  mutate(across(everything(), as.character)) |> 
  pivot_longer(everything(), names_to = "var")

ggplot(dat, aes(y = var))  
  geom_bar(data = ~subset(.x, var %in% c("X1", "X2")), aes(fill = value), position = "fill")  
  scale_fill_brewer(palette = "Accent", guide = guide_legend(order = 3))  
  new_scale_fill()  
  geom_bar(data = ~subset(.x, var %in% c("X3")), aes(fill = value), position = "fill")  
  scale_fill_brewer(palette = "Dark2", guide = guide_legend(order = 2))  
  new_scale_fill()  
  geom_bar(data = ~subset(.x, var %in% c("X4")), aes(fill = value), position = "fill")  
  scale_fill_brewer(palette = "Paired", guide = guide_legend(order = 1))

enter image description here

  • Related