我正在嘗試使用沖積圖(桑基圖)來顯示兩個時間段內不同類別的變化。當所有因子水平都在兩個時間段(前和后)中表示時,我能夠創建一個對我有意義的圖,但是對于我的資料,在更改因子順序后,該圖看起來很奇怪。我還想為兩個時間段的類別顯示相同的填充顏色,但只能更改第一個時間段(前)。當我畫圖時,我注意到我指定的顏色不是我想要的每個因子水平的顏色,盡管框/層的順序是正確的。
關于如何改進情節以及我如何克服在兩個時間段中沒有完全代表類別時對兩個組的因子水平進行排序的問題的任何幫助或建議都會非常有幫助。
這是代碼:
db <- read.table(text = "pre post freq
NE NE 0
NE DD 2
NE LC 5
NE NT 2
NE VU 3
NE EN 5
NE CR 1
DD NE 0
DD DD 3
DD LC 37
DD NT 10
DD VU 14
DD EN 3
DD CR 3
LC NE 0
LC DD 0
LC LC 18
LC NT 2
LC VU 1
LC EN 2
LC CR 0
NT NE 0
NT DD 1
NT LC 3
NT NT 8
NT VU 13
NT EN 5
NT CR 1
VU NE 0
VU DD 0
VU LC 1
VU NT 0
VU VU 7
VU EN 8
VU CR 3
EN NE 0
EN DD 0
EN LC 0
EN NT 0
EN VU 0
EN EN 0
EN CR 2
CR NE 0
CR DD 0
CR LC 1
CR NT 0
CR VU 0
CR EN 0
CR CR 2
", header=T)
head(db)
# Order factor levels
levels(db$pre) <- c("NE", "DD", "LC", "NT", "VU", "EN", "CR")
levels(db$post) <- c("NE", "DD", "LC", "NT", "VU", "EN", "CR")
# Set colors for the plot
colors.p <- c("#282828", "#7C7C7C", "#20AB5F", "#3EFF00",
"#FBFF00", "#FFBD00", "#FF0C00")
# Plot
p <- ggplot(db,
aes(y = freq, axis1 = pre,
axis2 = post))
geom_alluvium(aes(fill = pre), show.legend = FALSE)
geom_stratum(aes(fill = pre), color = "black", alpha = 0.5)
geom_label(stat = "stratum", aes(label = after_stat(stratum)))
scale_x_discrete(limits = c("previous", "current"),
expand = c(0.3, 0.01))
scale_fill_manual(values = colors.p)
theme_void()
theme(
panel.background = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size = 15, face = "bold"),
axis.title = element_blank(),
axis.ticks = element_blank(),
legend.position = "none"
)
p
uj5u.com熱心網友回復:
我
編輯:對于您的新資料,我之前發布的方法仍然有效。您需要在前時間點的因子重新調整中添加附加級別(“NE”)并作為新顏色(在本例中為藍色)。您對這些資料有什么錯誤?
library(tidyverse)
library(ggsankey)
db <- read.table(text = "pre post freq
NE NE 0
NE DD 2
NE LC 5
NE NT 2
NE VU 3
NE EN 5
NE CR 1
DD NE 0
DD DD 3
DD LC 37
DD NT 10
DD VU 14
DD EN 3
DD CR 3
LC NE 0
LC DD 0
LC LC 18
LC NT 2
LC VU 1
LC EN 2
LC CR 0
NT NE 0
NT DD 1
NT LC 3
NT NT 8
NT VU 13
NT EN 5
NT CR 1
VU NE 0
VU DD 0
VU LC 1
VU NT 0
VU VU 7
VU EN 8
VU CR 3
EN NE 0
EN DD 0
EN LC 0
EN NT 0
EN VU 0
EN EN 0
EN CR 2
CR NE 0
CR DD 0
CR LC 1
CR NT 0
CR VU 0
CR EN 0
CR CR 2
", header=T)
db %>%
uncount(freq) %>%
make_long(pre, post) %>%
mutate(node = fct_relevel(node,"DD", "LC", "NT","NE", "VU", "EN", "CR"),
next_node = fct_relevel(next_node, "DD", "LC", "NT", "VU", "EN", "CR")) %>%
ggplot(aes(x = x,
next_x = next_x,
node = node,
next_node = next_node,
fill = factor(node)))
geom_alluvial()
scale_fill_manual(values = c("DD" = "#7C7C7C", "LC" = "#20AB5F", "NT" = "#3EFF00", "VU" = "#FBFF00", "EN" = "#FFBD00", "CR" = "#FF0C00", "NE" ="blue"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341818.html
下一篇:geom_line不顯示線
