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

求助:ggplot中无法按数值对柱状图进行排序

解决ggplot柱状图按数值排序的问题

你的问题出在排序逻辑上:fct_infreq()是按照类别出现的频率排序,而你这里每个Country都是唯一值,所以这个函数根本起不到按Spending_2020数值排序的作用。

下面给你两种可行的修正方案:

方案一:用forcats::fct_reorder()直接指定排序依据

直接在因子处理时,用fct_reorder()把Country按照Spending_2020的数值排序,配合coord_flip()调整显示方向:

#Load any packages 
library(ggplot2)
library(dplyr)
library(forcats)

#Create data frame
MarketSize <- data.frame(Country = c("United States", "Japan", "Germany", "France", "Italy", "United Kingdom", "Spain", "Canada", "South Korea",
                                     "Australia", "China", "Brazil", "Russia", "India", "Other"),
                            Spending_2020 = c(528.7, 88.2, 54.9, 36.3, 33.3, 30.2, 25.7, 22.8, 16.2, 11.8, 134.4, 28.7, 17.5, 21.5, 15)
)

# 按Spending_2020数值从小到大排序Country因子,coord_flip后会变成从下到上递增
MarketSize$Country <- fct_reorder(MarketSize$Country, MarketSize$Spending_2020)
# 如果想要从大到小排序,添加.desc=TRUE参数:
# MarketSize$Country <- fct_reorder(MarketSize$Country, MarketSize$Spending_2020, .desc = TRUE)

#Create plot, labels etc.
MarketSize_2020 <- ggplot(MarketSize, aes(x = Country, y = Spending_2020)) + 
  geom_col(fill="steelblue", width=0.75) +
  geom_text(aes(label=Spending_2020), vjust=0.5, hjust=-0.01, size=3.5) +
  coord_flip() +
  labs(title = "Market Spending on pharmaceuticals, 2020",
       x = "Country or region",
       y = "Total spending on pharmaceuticals (US $BN)") +
  theme_classic() 

#View plot
MarketSize_2020

方案二:用dplyr先排序数据再转因子

先通过arrange()把数据按Spending_2020排序,再把Country转为因子(因子的水平顺序会继承数据框的行顺序):

#Load any packages 
library(ggplot2)
library(dplyr)

#Create data frame
MarketSize <- data.frame(Country = c("United States", "Japan", "Germany", "France", "Italy", "United Kingdom", "Spain", "Canada", "South Korea",
                                     "Australia", "China", "Brazil", "Russia", "India", "Other"),
                            Spending_2020 = c(528.7, 88.2, 54.9, 36.3, 33.3, 30.2, 25.7, 22.8, 16.2, 11.8, 134.4, 28.7, 17.5, 21.5, 15)
)

# 先按Spending_2020排序,再把Country转为因子
MarketSize <- MarketSize %>%
  arrange(Spending_2020) %>%  # 从小到大排序,想要从大到小就用arrange(desc(Spending_2020))
  mutate(Country = factor(Country, levels = Country))

#Create plot, labels etc.
MarketSize_2020 <- ggplot(MarketSize, aes(x = Country, y = Spending_2020)) + 
  geom_col(fill="steelblue", width=0.75) +
  geom_text(aes(label=Spending_2020), vjust=0.5, hjust=-0.01, size=3.5) +
  coord_flip() +
  labs(title = "Market Spending on pharmaceuticals, 2020",
       x = "Country or region",
       y = "Total spending on pharmaceuticals (US $BN)") +
  theme_classic() 

#View plot
MarketSize_2020

两种方法都能让柱状图按Spending_2020的数值排序,你可以根据自己的习惯选择。如果需要从大到小排列,只需要在排序时加上对应参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:35:13