首页 > 解决方案 > 如何使用 ggplot2 制作冲积图以显示来自 spss 的交叉制表结果?

问题描述

这是我的数据:

 df <- structure(list(language = c("German", "German", "German", "German", 
"German", "German", "German", "German", "French", "French", "French", 
"French", "French", "French", "French", "French", "Italian", 
"Italian", "Italian", "Italian", "Italian", "Italian", "Italian", 
"Italian"), main_variable = c("d02a", "d02a", "d02a", "d02a", 
"d02a", "d02a", "d02a", "d02a", "d02a", "d02a", "d02a", "d02a", 
"d02a", "d02a", "d02a", "d02a", "d02a", "d02a", "d02a", "d02a", 
"d02a", "d02a", "d02a", "d02a"), combination1 = c("very_attached", 
"very_attached", "quite_attached", "quite_attached", "rather_only_sympathiser", 
"rather_only_sympathiser", "not_attached_to_a_party", "not_attached_to_a_party", 
"very_attached", "very_attached", "quite_attached", "quite_attached", 
"rather_only_sympathiser", "rather_only_sympathiser", "not_attached_to_a_party", 
"not_attached_to_a_party", "very_attached", "very_attached", 
"quite_attached", "quite_attached", "rather_only_sympathiser", 
"rather_only_sympathiser", "not_attached_to_a_party", "not_attached_to_a_party"
), combination2 = c("male", "female", "male", "female", "male", 
"female", "male", "female", "male", "female", "male", "female", 
"male", "female", "male", "female", "male", "female", "male", 
"female", "male", "female", "male", "female"), count = c(24L, 
23L, 56L, 42L, 78L, 75L, 183L, 218L, 4L, 2L, 12L, 22L, 24L, 33L, 
48L, 68L, 3L, 3L, 8L, 9L, 4L, 3L, 5L, 9L)), class = "data.frame", row.names = c(NA, 
-24L))

是否可以制作类似的图表?

这个

我想制作一个图来显示像这样的spss交叉制表的结果数据框具有该表的结构,但是如果在向数据框的传输过程中出现任何错误,我可以对其进行更新。

标签: rggplot2

解决方案


您可以尝试以下方法:

library(tidyverse)
library(ggalluvial)

df %>%
  ggplot(aes(y = count, axis1 = combination2, axis2 = language, axis3 = combination1)) +
  geom_alluvium(aes(fill = combination1), width = 0, knot.pos = 0, reverse = FALSE) +
  guides(fill = FALSE) +
  geom_stratum(width = 1/8, reverse = FALSE) +
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), reverse = FALSE) +
  scale_x_continuous(breaks = 1:3, labels = c("Sex", "Language", "attachment level")) +
  ggtitle("This is a title")

推荐阅读