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

如何按Group1(G1)数值降序重新排序ggplot分组条形图的x轴国家?

按G1数值降序排列条形图x轴国家的解决方案

你之前的代码用reorder(country, -Value)无效,是因为reorder默认会对每个国家的所有Value取均值(默认FUN=mean),实际是按G1+G2的平均值排序,自然不符合只按G1排序的需求。以下两种方法可以解决问题:

方法1:预处理数据设置因子水平

先提取G1的数据并按数值降序确定国家顺序,再把原数据的country转为因子指定排序:

# 获取G1数值降序的国家顺序
g1_sorted <- df[df$Variable == "G1", ] |> 
  arrange(-Value) |> 
  pull(country)

# 将country转换为因子,固定排序
df$country <- factor(df$country, levels = g1_sorted)

# 绘图
ggplot(data = df, aes(country, Value, fill = Variable)) +
  geom_bar(position = "dodge", stat = "identity")

方法2:在ggplot中直接指定排序依据

无需预处理数据,用ave函数仅提取每个国家G1的数值作为排序依据:

ggplot(data = df,
       aes(reorder(country, -ave(Value, country, FUN = function(x) x[Variable == "G1"])), 
           Value, fill = Variable)) +
  geom_bar(position = "dodge", stat = "identity")

两种方法都能让x轴国家按G1数值从高到低排列:DE(24)→ PL(12)→ FR(6),完全符合你的需求。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:31:04