You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:57:03