R语言 混合变量堆叠条形图

vlf7wbxs  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(143)

我想制作一个GGPlot堆叠条形图,变量在水平轴上,但有些变量有不同的响应。
有些变量是“是/否”回答,有些变量是“老/年轻”,有些变量是0-5的李克特量表。
因此,我想以堆叠条形图的形式绘制这些变量,每个变量类型用不同的调色板编码,并用图例反映不同的调色板/变量类型。
我想知道是否有人能帮上忙,拜托了?我会非常感激的。

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)
6yoyoihd

6yoyoihd1#

实现理想结果的一种选择是使用ggnewscale包,该包允许使用多种比例和图例,以实现相同的美学效果:

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))

相关问题