如何调整ggalluvial冲积图的层级顺序?
如何调整ggalluvial冲积图的层级顺序?
我太懂你这个困扰了!之前我也碰到过改了因子水平,但冲积图的矩形顺序还是乱的情况——问题出在你只调整了因子的层级,却没让ggplot的图层和scale同步识别这个顺序。咱们一步步来解决:
首先,你之前写的rlevels应该是拼写错误啦,正确的方式是用factor()或者forcats包的函数来重新指定response的因子水平顺序,这是基础:
# 用基础R直接设置因子水平,顺序就是你要的从上到下 vaccinations$response <- factor(vaccinations$response, levels = c("Sometimes", "always", "missing", "never")) # 如果习惯用tidyverse的话,用forcats包更顺手: # library(forcats) # vaccinations$response <- fct_relevel(vaccinations$response, "Sometimes", "always", "missing", "never")
接下来,在你的ggplot代码里,需要明确让填充色的scale跟着咱们设置的因子顺序走,不然ggalluvial可能还是会用默认的排序逻辑。把完整代码改成这样:
library(ggalluvial) # 先搞定因子水平 vaccinations$response <- factor(vaccinations$response, levels = c("Sometimes", "always", "missing", "never")) ggplot(data = vaccinations, aes(axis1 = survey, axis2 = response, y = freq)) + geom_alluvium(aes(fill = response)) + geom_stratum(aes(fill = response)) + geom_text(stat = "stratum", aes(label = after_stat(stratum))) + scale_x_discrete(limits = c("Survey", "Response"), expand = c(0.15, 0.05)) + # 关键:让填充色的顺序和因子水平完全一致 scale_fill_discrete(limits = levels(vaccinations$response)) + theme_void()
为什么之前的方法没用呢?因为仅仅修改因子水平后,ggplot的scale_fill_discrete可能还会按字母顺序或者默认规则排序,加上limits = levels(vaccinations$response)就能强制它跟着咱们设定的顺序来,这样冲积图的矩形就会从上到下严格对应你要的Sometimes→always→missing→never啦!
备注:内容来源于stack exchange,提问作者Tpellirn
相关产品推荐
相关产品推荐

