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

如何获取数据框唯一字符值频率?reorder与count正确用法及报错解决

问题解决:按频率排序的居住州条形图

需求

绘制条形图,将state.of.res(居住州)置于y轴,各居住州的出现频率置于x轴,并按频率从高到低排序。

原代码

customers %>%
  ggplot(aes(x = reorder(state.of.res, count(as.factor(state.of.res), wt = NULL, sort = TRUE, name = "Observations")))) +
  geom_bar(aes(fill = state.of.res)) +
  coord_flip() +
  theme(legend.position = "none")+
  labs(y = "Count ->", x = "State of Residence ->")

报错信息

Error in `geom_bar()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `UseMethod()`:
! no applicable method for 'count' applied to an object of class "factor"
Run `rlang::last_trace()` to see where the error occurred.

错误原因

count()是dplyr包中用于统计数据框分组行数的函数,不能直接作用于单个因子向量。原代码里把count()直接套在state.of.res(因子类型)上,触发了方法不匹配的错误。reorder()的第二个参数需要的是用于排序的数值,而非用count()处理单个向量的错误用法。

两种正确实现方式

方式一:先统计频率再绘图(推荐,逻辑清晰)

先通过count()统计每个州的观测数,再基于统计结果绘图:

library(dplyr)
library(ggplot2)

customers %>%
  # 统计每个州的数量,生成名为Observations的列
  count(state.of.res, name = "Observations") %>%
  # 按Observations的值对state.of.res排序
  ggplot(aes(x = reorder(state.of.res, Observations), y = Observations)) +
  # stat="identity"表示直接使用已有的数值绘制条形
  geom_bar(stat = "identity", aes(fill = state.of.res)) +
  coord_flip() +
  theme(legend.position = "none") +
  labs(y = "数量 ->", x = "居住州 ->")

方式二:直接在ggplot中使用内部统计变量

利用ggplot的after_stat(count)获取条形的计数,作为排序依据,无需提前处理数据:

library(ggplot2)

customers %>%
  ggplot(aes(x = reorder(state.of.res, after_stat(count)), y = after_stat(count))) +
  geom_bar(aes(fill = state.of.res)) +
  coord_flip() +
  theme(legend.position = "none") +
  labs(y = "数量 ->", x = "居住州 ->")

注:如果使用的是旧版ggplot2(<3.3.0),可以用..count..代替after_stat(count)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:28:25