使用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
变量,但似乎都不起作用。我也尝试将它们定义为字符并按不同顺序排序,但这似乎也不起作用。
任何帮助都将不胜感激。
答案 0 :(得分:2)
不确定您对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")
答案 1 :(得分:0)
如何将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')