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

R语言报错:plot.new hasn't been called yet 问题求助

解决R报错:"plot.new hasn't been called yet"

这个报错的核心原因很直白:你调用grid()的时机不对——必须先创建好绘图画布,再添加网格线,而不是反过来。

修正后的代码

# 先定义数据向量
porcentagem_sem_rep <- c(18.08, 8.73, 8.53, 8.33, 6.91, 6.70, 5.89, 4.67, 4.47, 3.45, 3.25, 3.04, 2.64, 2.43, 2.23, 2.23, 1.82, 1.82, 1.42, 1.01, 1.01, 0.60, 0.40, 0.20)

# 设置绘图边距
par(mar = c(10,6,6,6))

# 第一步:先创建基础绘图,初始化绘图区域
plot(porcentagem_sem_rep, ylim = c(0,20), xaxt = "n", xlab = "", ylab = "Exposição")

# 第二步:在已有的画布上添加网格线
grid(nx = 24, ny = 8, col = "lightgray", lty = "dotted")

为什么原代码会报错?

原代码里你先调用了grid(),但此时R还没有通过plot()创建任何绘图设备,它不知道要把网格画在哪里,所以就抛出了"plot.new hasn't been called yet"的错误——相当于你想在一张不存在的纸上画格子,肯定行不通嘛。

更简洁的写法(推荐)

如果想让网格线显示在数据点的下方(不被覆盖),可以直接用plot()的panel.first参数一步完成,不用单独调用grid():

porcentagem_sem_rep <- c(18.08, 8.73, 8.53, 8.33, 6.91, 6.70, 5.89, 4.67, 4.47, 3.45, 3.25, 3.04, 2.64, 2.43, 2.23, 2.23, 1.82, 1.82, 1.42, 1.01, 1.01, 0.60, 0.40, 0.20)

par(mar = c(10,6,6,6))

plot(porcentagem_sem_rep, ylim = c(0,20), xaxt = "n", xlab = "", ylab = "Exposição",
     panel.first = grid(nx = 24, ny = 8, col = "lightgray", lty = "dotted"))

内容的提问来源于stack exchange,提问作者Luís Henrique Martins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:19:51