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

如何解决ggplot中check_aesthetics错误并生成柱状图?

ggplot绘制柱状图报错Error in check_aesthetics(evaled, n)的解决方法

问题描述

我正在学习tidyverse,能够使用默认的barchart()生成柱状图,但使用ggplot绘制时遇到问题。所有对象长度一致,不确定在aes()中存在什么错误,报错信息为:Error in check_aesthetics(evaled, n)。相关代码如下:

### Sample data
df <- data.frame(a = c(sample(500:2000,50)),
                 b = c(sample(500:2000,50)),
                 c = c(sample(500:2000,50)),
                 d = c(sample(500:2000,50)),
                 e = c(sample(500:2000,50)),
                 f = c(sample(500:2000,50)),
                 g = c(sample(500:2000,50)),
                 h = c(sample(500:2000,50)),
                 i = c(sample(500:2000,50)),
                 j = c(sample(500:2000,50)),
                 k = c(sample(500:2000,50)),
                 l = c(sample(500:2000,50)),
                 m = c(sample(500:2000,50)),
                 n = c(sample(500:2000,50)))

### Assign values to objects    
totals <- apply(df, 2, sum)
names <- c(colnames(df))
### Create bar chart    
ggplot(df, aes(x = names, y = totals)) + geom_bar(stat = "identity")

错误原因

报错的核心问题是:ggplot的data参数传入的是原始的df(共50行),但aes()中使用的names和totals是长度为14的向量。ggplot要求美学映射变量的长度必须与data的行数一致,这里50和14不匹配,因此触发了check_aesthetics的校验错误。

解决方法

需要将统计好的列名和对应总和整理成一个新的数据集,再传入ggplot:

方法1:基础R实现

# 创建汇总后的数据集
summary_df <- data.frame(
  names = colnames(df),
  totals = apply(df, 2, sum)
)

# 绘制柱状图
ggplot(summary_df, aes(x = names, y = totals)) + 
  geom_bar(stat = "identity")

方法2:tidyverse风格实现(更推荐)

library(tidyverse)

df %>%
  summarise(across(everything(), sum)) %>% # 计算每列的总和
  pivot_longer(everything(), names_to = "names", values_to = "totals") %>% # 宽表转长表
  ggplot(aes(x = names, y = totals)) +
  geom_bar(stat = "identity")

内容的提问来源于stack exchange,提问作者professor.luther.ratigan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:35:21