如何让R中ggplot的geom_segment()可视化结果按降序排列
问题根因
你在ggplot全局映射中仅对x轴做了因子重排序,但geom_segment单独指定的x = source调用的是原数据中未经过排序的source字段,两层映射的排序规则不一致,最终导致排序失效。
解决方案
推荐优先通过预处理数据集统一字段排序,逻辑更清晰,后续所有图层调用时都不会出现排序冲突:
# 若未加载forcats包需先加载,tidyverse已内置该包 library(tidyverse) # 提前将source列按n降序重排为因子 device <- device %>% mutate(source = fct_reorder(source, n, .desc = TRUE)) # 绘图时直接使用处理好的source列即可 ggplot(data = device, mapping = aes(x = source, y = n)) + geom_segment(aes(x = source, xend = source, y = 0, yend = n)) + theme(axis.text.x = element_text(angle = 90, hjust = 1, family = "sans")) + labs(title = "Tweets by device/source", x = "device/source", y = "frequency") + geom_point(size = 4, color = "red", fill = alpha("yellow", 0.3), alpha = 0.7, shape = 21, stroke = 2)
如果不想修改原数据集,也可以统一所有图层的x映射规则,将geom_segment中的x和xend参数都替换为重排序后的表达式即可,不过该方式代码冗余度更高,不推荐使用。
内容的提问来源于stack exchange,提问作者tores
相关产品推荐
相关产品推荐

