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

R语言fct_infreq函数正确用法:如何让ggplot条形图按数值排序

解决方案

你需要调整国家列GEO.SRC_FUND的因子排序逻辑,直接在ggplot的美学映射(aes)中修改该列即可。你查询到的fct_infreq适用于按国家出现的频次排序的场景,你当前需要匹配Public.funding的数值排序,更推荐使用fct_reorder函数,修改后的完整代码如下:

library(tidyverse)

df_a <- read.csv(file = "inn_cis10_pub.csv", head = TRUE, sep = ";")

df_a %>%
  drop_na(Public.funding) %>%
  ggplot(aes(fct_reorder(GEO.SRC_FUND, Public.funding), Public.funding))+
  geom_bar(stat='identity')+
  coord_flip()+
  theme_bw()+
  labs(y = "Public funding",
       x = "Country",
       title = "Public funding per country")

可选参数调整

  • 如果你需要条形按数值从大到小排列(翻转后从上到下数值从高到低),可以给fct_reorder加降序参数,写成fct_reorder(GEO.SRC_FUND, Public.funding, .desc = TRUE)
  • 如果你确实需要使用fct_infreq按国家出现频次排序,直接将上述代码里的fct_reorder部分替换为fct_infreq(GEO.SRC_FUND)即可,放置位置完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:54:01