8

使用 ggforce 包的开发版本,我可以如下创建一个 Sankey 图(来自文档)

data <- reshape2::melt(Titanic)
data <- gather_set_data(data, 1:4)

ggplot(data, aes(x, id = id, split = y, value = value)) +
  geom_parallel_sets(aes(fill = Sex), alpha = 0.3, axis.width = 0.1) +
  geom_parallel_sets_axes(axis.width = 0.1) +
  geom_parallel_sets_labels(colour = 'white')

在此处输入图像描述

我正在苦苦挣扎的是,以默认方式以外的任何方式对 y 轴变量进行排序,这似乎是反向字母顺序。例如,将绘图更改为Adult出现在绘图顶部附近,Child如下所示。

我尝试在应用之前重新调整因子gather_set_data,以及在应用y之后重新调整变量gather_set_data,但似乎都不起作用。我也尝试将它们定义为字符并以不同的顺序排序,但这似乎也不起作用。

任何帮助,将不胜感激。

4

2 回答 2

3

不确定你会做什么,ggforce因为我不使用这个包。我认为解决方案是重新调整您提到的因素,但这似乎对您不起作用。但是,这确实适用于ggalluvial. 此外,还有一个参数reverse允许您颠倒顺序(字母顺序/逆字母顺序)。见下文:

默认排序

library(ggplot2)
library(ggalluvial)

df <- as.data.frame(Titanic)

ggplot(as.data.frame(df),
       aes(weight = Freq,
           axis1 = Survived, axis2 = Sex, axis3 = Class)) +
  geom_alluvium(aes(fill = Class),
                width = 0, knot.pos = 1/4, reverse = FALSE) +
  guides(fill = FALSE) +
  geom_stratum(width = 1/8, reverse = FALSE) +
  geom_text(stat = "stratum", label.strata = TRUE, reverse = FALSE) +
  scale_x_continuous(breaks = 1:3, labels = c("Survived", "Sex", "Class")) +
  ggtitle("Titanic survival by class and sex")

在此处输入图像描述

逆序

ggplot(as.data.frame(df),
       aes(weight = Freq,
           axis1 = Survived, axis2 = Sex, axis3 = Class)) +
  geom_alluvium(aes(fill = Class),
                width = 0, knot.pos = 1/4, reverse = TRUE) +
  guides(fill = FALSE) +
  geom_stratum(width = 1/8, reverse = TRUE) +
  geom_text(stat = "stratum", label.strata = TRUE, reverse = TRUE) +
  scale_x_continuous(breaks = 1:3, labels = c("Survived", "Sex", "Class")) +
  ggtitle("Titanic survival by class and sex")

在此处输入图像描述

再调平系数

df$Class <- factor(df$Class, levels = c("3rd", "1st", "Crew", "2nd"))

ggplot(as.data.frame(df),
       aes(weight = Freq,
           axis1 = Survived, axis2 = Sex, axis3 = Class)) +
  geom_alluvium(aes(fill = Class),
                width = 0, knot.pos = 1/4, reverse = FALSE) +
  guides(fill = FALSE) +
  geom_stratum(width = 1/8, reverse = FALSE) +
  geom_text(stat = "stratum", label.strata = TRUE, reverse = FALSE) +
  scale_x_continuous(breaks = 1:3, labels = c("Survived", "Sex", "Class")) +
  ggtitle("Titanic survival by class and sex")

在此处输入图像描述

于 2017-12-11T23:39:22.233 回答
1

如何将 y 变量更改为因子如下?

    titanic <- reshape2::melt(Titanic)
    titanic <- gather_set_data(titanic, 1:4)
    titanic$y <- factor(titanic$y, levels=c("Adult", "Child", "1st", "2nd", "3rd", "Crew", "Male", "Female", "Yes", "No"))
    ggplot(titanic, aes(x, id = id, split = y, value = value)) +
        geom_parallel_sets(aes(fill = Sex), alpha = 0.3, axis.width = 0.1) +
        geom_parallel_sets_axes(axis.width = 0.1) +
        geom_parallel_sets_labels(colour = 'white')
于 2020-10-30T01:50:00.137 回答