使用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
变量,但似乎都不起作用。我也尝试过将它们定义为字符并按不同顺序排序,但这似乎也不起作用。任何帮助,将不胜感激。
最佳答案
由于我不使用此软件包,因此不确定您对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")