您好,我通常使用如下的代码来重新排序ggplot或其他类型的图中的条形码 .
Normal plot (unordered)
library(tidyverse)
iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
select(mSW,Species) %>%
distinct()
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) +
geom_point(stat = "identity")
Ordering the factor + ordered plot
iris.tr$Species <- factor(iris.tr$Species,
levels = iris.tr[order(iris.tr$mSW),]$Species,
ordered = TRUE)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) +
geom_point(stat = "identity")
因素线对我来说非常不愉快,我想知道为什么 arrange()
或其他一些功能无法简化这一点 . 我错过了什么?
Note:
这不起作用,但我想知道tidyverse中是否存在这样的东西 .
iris.tr <-iris %>% group_by(Species) %>% mutate(mSW = mean(Sepal.Width)) %>%
select(mSW,Species) %>%
distinct() %>%
arrange(mSW)
ggplot(iris.tr,aes(x = Species,y = mSW, color = Species)) +
geom_point(stat = "identity")
2 回答
使用base重新排序因子:
转换为
dplyr
:之后,您可以继续进行总结并在问题中进行绘图 .
几条评论:重新排序因素是修改数据列 . 用于修改数据列的
dplyr
命令是mutate
. 所有arrange
都重新排序行,这对因子的级别没有影响,因此对ggplot中的图例或轴的顺序没有影响 .所有因素都有订单 .
ordered = TRUE
因子与常规因子之间的差异在于如何在模型中设置对比度 . 只有当您的因子级别具有有意义的排名顺序时才应该使用ordered = TRUE
,例如"Low","Medium","High",即使这样,只有在构建模型并且不希望默认对比将所有内容与参考级别进行比较时才会使用ordered = TRUE
.使用<forcats>: