您遇到的错误 Error in plot.new() : figure margins too large 表示图形设备的大小不足以容纳绘图所需的边距。这通常发生在RStudio的绘图面板较小或图形边距设置过大时。以下是几种解决方案:
解决方案1:扩大绘图设备
在RStudio中,最简单的方法是直接拖动绘图面板的边界,扩大绘图区域。
解决方案2:调整图形边距
通过par()函数减小图形边距设置:
# 设置更小的图形边距
par(mar = c(3, 3, 2, 1)) # 下、左、上、右的边距
# 然后绘图
plot(sales, main = "薯片销售量", ylab = "销售量", type = "l")
解决方案3:使用ggplot2绘图(推荐)
ggplot2能更好地自动调整图形布局:
library(ggplot2)
# 创建数据框
ts_data <- data.frame(
Time = time(sales),
Sales = as.numeric(sales)
)
# 使用ggplot2绘图
ggplot(ts_data, aes(x = Time, y = Sales)) +
geom_line(color = "blue", linewidth = 0.8) +
labs(title = "Bluebird薯片销售量", x = "时间", y = "销售量") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 14),
panel.grid.minor = element_blank()
)
完整修正后的代码:
# 加载必要的包
library(TSA) # 包含bluebird数据集
library(forecast) # 时间序列建模和预测
library(tseries) # 时间序列检验
library(lmtest) # 模型诊断检验
library(ggplot2) # 数据可视化
# 加载数据集
data(bluebird)
sales <- bluebird[, "sales"]
price <- bluebird[, "price"]
# 1. 数据可视化(使用ggplot2避免边距问题)
# 销售序列
ggplot(data.frame(Time = time(sales), Sales = as.numeric(sales)),
aes(x = Time, y = Sales)) +
geom_line(color = "blue", linewidth = 0.8) +
labs(title = "Bluebird薯片销售量", x = "时间", y = "销售量") +
theme_minimal()
# 价格序列
ggplot(data.frame(Time = time(price), Price = as.numeric(price)),
aes(x = Time, y = Price)) +
geom_line(color = "red", linewidth = 0.8) +
labs(title = "Bluebird薯片价格", x = "时间", y = "价格") +
theme_minimal()
# 2. 平稳性检验(ADF单位根检验)
adf_sales <- adf.test(sales)
adf_price <- adf.test(price)
cat("销售序列ADF检验p值:", adf_sales$p.value, "\n")
cat("价格序列ADF检验p值:", adf_price$p.value, "\n")
# 3. 互相关分析(CCF)
ccf_result <- ccf(sales, price, lag.max = 12,
main = "销售与价格的互相关函数",
ylab = "互相关",
xlab = "滞后阶数")
# 识别显著滞后阶数
n <- length(sales)
significant_lags <- which(abs(ccf_result$acf) > 2/sqrt(n)) - (12 + 1)
cat("显著的滞后阶数:", significant_lags, "\n")
# 4. 建立ARIMAX模型
# 确保使用矩阵形式的外生变量
price_matrix <- as.matrix(price)
arimax_model <- auto.arima(
sales,
xreg = price_matrix,
stepwise = FALSE,
approximation = FALSE,
seasonal = FALSE,
trace = TRUE # 显示模型选择过程
)
# 显示模型摘要
summary(arimax_model)
# 5. 模型诊断
# 残差自相关检验
checkresiduals(arimax_model)
# 残差正态性检验
jarque.bera.test(residuals(arimax_model))
# 6. 模型系数显著性检验
coeftest(arimax_model)
# 7. 模型比较
arima_model <- auto.arima(sales, seasonal = FALSE)
cat("\n模型比较:\n")
cat("ARIMAX模型AIC:", arimax_model$aic, "\n")
cat("普通ARIMA模型AIC:", arima_model$aic, "\n")
关键修改说明:
-
图形绘制:
- 使用
ggplot2替代基础绘图函数,避免边距问题
- 添加更美观的图形元素(颜色、标题、主题)