R脚本命令行运行报错stat_count()需x/y美学映射,RStudio运行正常
stat_count() requires an x or y aesthetic 问题背景
我正在做一个项目,需要从命令行传入CSV和PDF文件名,把频率柱状图保存到PDF里。这段代码在RStudio里运行完全正常,但命令行执行时就报错:stat_count() requires an x or y aesthetic。
代码如下:
generation_freq <- data |> dplyr::filter(score != 0) |> as.data.frame() ggGeneration <- ggplot(data = generation_freq, mapping = aes(x = generation)) + geom_bar(stat = "count", color = "black", fill = "skyblue") + labs(x = "Generation", y = "Number of Correct Guesses", title = "Number of Correct Guesses vs Generation of the Pokemon") + theme(axis.text.x = element_text(angle = 0)) + scale_x_continuous("Generation", labels = as.character(generation_freq$generation), breaks = generation_freq$generation) ggsave(filename = generationsPlot,plot = ggGeneration)
其中data是从CSV读取的数据集,generationsPlot是保存图表的PDF文件名。我查过类似报错,大多是因为geom_bar()没指定非计数的y轴,但我的情况不一样。
generation_freq样本数据:
structure(list(mystery.pokemon = c("Charmander", "Gligar", "Mantine", "Slowking", "Wurmple", "Makuhita", "Overqwil", "Toucannon", "Exeggutor", "Victini", "Corvisquire", "Espurr", "Gigalith", "Toxel", "Litleo", "Vibrava", "Furfrou"), generation = c(1L, 2L, 2L, 2L, 3L, 3L, 8L, 7L, 1L, 5L, 8L, 6L, 5L, 8L, 6L, 3L, 6L), hints = c(2L, 7L, 3L, 6L, 4L, 3L, 2L, 3L, 4L, 5L, 6L, 7L, 7L, 6L, 7L, 5L, 7L), guesses = c(1L, 0L, 4L, 1L, 0L, 0L, 3L, 0L, 3L, 0L, 0L, 0L, 0L, 0L, 0L, 2L, 0L), score = c(8L, 3L, 7L, 4L, 6L, 7L, 8L, 7L, 6L, 5L, 4L, 3L, 3L, 4L, 3L, 5L, 3L)), class = "data.frame", row.names = c(NA, -17L))
报错原因
核心问题是命令行环境下,generation_freq可能是空数据框。
你代码里用dplyr::filter(score != 0)筛选数据,如果命令行中读取的CSV文件里所有score值都是0,或者读取CSV时出了问题(比如文件路径不对、文件名拼写错误,导致data本身是空的),那么generation_freq就会变成空数据框。
当ggplot处理空数据框时,即使你在aes()里指定了x=generation,由于没有数据,ggplot无法识别这个变量的存在,就会抛出stat_count() requires an x or y aesthetic的错误——这和你查到的“没指定y轴”的情况本质不同,是因为数据为空导致的变量缺失。
另外,还有一个潜在问题:你用scale_x_continuous时直接引用generation_freq$generation,如果generation_freq为空,这部分也会出问题。
验证方法:在命令行运行代码时,加一行print(nrow(generation_freq)),看看输出是不是0。如果是0,就检查CSV文件的读取逻辑和文件内容。
内容的提问来源于stack exchange,提问作者Owen Daley

