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

如何在R的plot.xts(当前xts版本)中绘制双序列双Y轴图

在新版xts中实现双Y轴同图绘制

没问题,我帮你梳理下在当前版本xts里怎么把两个序列画在同一图表并使用不同Y轴。其实核心思路是先画第一个序列,再开启新的绘图上下文来画第二个序列,同时指定右侧Y轴,具体步骤和代码如下:

首先,先保留你的示例数据生成代码(这段代码在新版xts里依然可以正常运行):

library(xts)
set.seed(190)
modelo_1 <- arima.sim(n = 252*8,list(ar = c(.99999),sd = sqrt(0.5)))
set.seed(256)
modelo_2 <- arima.sim(n = 252*8,list(ar = c(.9999),sd = sqrt(0.75)))
d1 <- as.Date("2008-01-01")
series_1 <- xts(modelo_1, seq(d1, by = "days", along.with = modelo_1))
series_2 <- xts(modelo_2, seq(d1, by = "days", along.with = modelo_2))

接下来是实现双Y轴绘图的关键代码:

# 1. 绘制第一个序列,配置左侧Y轴样式
plot(series_1, col = "blue", main = "双Y轴时间序列图", ylab = "Series 1", lwd = 2)

# 2. 开启新绘图层,不清除现有图表内容
par(new = TRUE)

# 3. 绘制第二个序列,隐藏默认轴避免重复,之后手动添加右侧Y轴
plot(series_2, col = "red", ylab = "", xlab = "", axes = FALSE, lwd = 2)
axis(side = 4)  # 添加右侧Y轴刻度
mtext("Series 2", side = 4, line = 3)  # 添加右侧Y轴标签

# 4. 添加图例区分两个序列
legend("topleft", legend = c("Series 1", "Series 2"), col = c("blue", "red"), lwd = 2)

关键细节说明:

  • par(new=TRUE)是实现叠加绘图的核心,它允许我们在现有图表上绘制新内容,而不是清除重画
  • 绘制第二个序列时设置axes=FALSE,避免重复显示X轴和左侧Y轴,之后通过axis(side=4)手动添加右侧Y轴
  • 用mtext给右侧Y轴添加标签,保证布局美观不拥挤
  • 通过col和lwd参数设置不同的线条样式,让两个序列的区分度更高

如果你想更简洁一点,也可以用lines.xts来添加第二个序列,效果是一样的:

plot(series_1, col = "blue", main = "双Y轴时间序列图", ylab = "Series 1", lwd = 2)
par(new = TRUE)
lines(series_2, col = "red", lwd = 2)
axis(side = 4)
mtext("Series 2", side = 4, line = 3)
legend("topleft", legend = c("Series 1", "Series 2"), col = c("blue", "red"), lwd = 2)

这两种方式都能完美适配当前版本的xts,实现你想要的双Y轴同图效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:53:23