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

R运行ggplot2代码出现attempt to apply non-function报错求助

问题根源
  • 核心报错触发原因是ggplot语法书写错误:你在图层拼接时使用了(main = "Car Milage Data") (xlab = "Number of Cylinders")的写法,R会将前一个括号的运算结果识别为待调用的函数,而返回的字符串不是可调用函数,因此触发attempt to apply non-function报错。ggplot2中设置图表标题、坐标轴标签需要使用对应的函数,再通过+和图形容器拼接。
  • 额外语法问题:geom_col的color、fill参数如果传入固定颜色值,需要用引号包裹,否则R会将blue、green识别为变量,在找不到对应变量时也会触发报错。
修正后可运行代码

两种写法均可正常运行:

写法1:使用labs()统一设置标签

# install packages
install.packages("Ecdat")
install.packages("gapminder")
# run libraries
library(gapminder)
library(Ecdat)
library(ggplot2)
library(dplyr)

View(mtcars)

c <- ggplot(mtcars, aes(x = cyl, y=mpg))
c + geom_col(color = "blue", fill = "green") + 
  labs(
    main = "Car Milage Data",
    x = "Number of Cylinders",
    y = "Miles Per Gallon"
  )

写法2:单独调用标签函数

c <- ggplot(mtcars, aes(x = cyl, y=mpg))
c + geom_col(color = "blue", fill = "green") + 
  ggtitle("Car Milage Data") +
  xlab("Number of Cylinders") +
  ylab("Miles Per Gallon")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:45:03