R多个时间序列xts的图,只有1个图例

时间:2018-06-10 17:05:05

标签: r xts

我想在不同的窗口中生成时间序列xts对象的多个图形。问题是我不能只添加一个图例(最后一个图)。我的代码如下:

dev.new(width=3,height=9)
par(mfrow=c(3,1))
plot(csum_GVMP[,c(-2,-3)],main=" ",minor.ticks="years",cex.axis = 1,major.ticks="years",grid.ticks.on=FALSE,grid.ticks.lty=0,col=color)
addLegend("bottomleft",legend.names = c("","","","","","",""))
plot(csum_ERC[,c(-2,-3)],main=" ",minor.ticks="years",cex.axis = 1,major.ticks="years",grid.ticks.on=FALSE,grid.ticks.lty=0,col=color)
addLegend("bottomleft",legend.names = c("","","","","","",""))
plot(csum_MD[,c(-2,-3)],main=" ",minor.ticks="years",cex.axis = 1,major.ticks="years",grid.ticks.on=FALSE,grid.ticks.lty=0,col=color)

如您所见,我为第一个和第二个绘图添加了图例名称的空白值,但结果是相同图表的图表重复了两次,如下所示:仅显示csum_GVMP的图表 这里 enter image description here 否则如果我离开addLegend,情节就像这样, enter image description here

这就是我想要的,但现在我只想添加一个传奇。如果我省略第一和第二个图的addLegend命令,则数字甚至不会被绘制。 有人知道怎么办吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

你去吧。如果取消注释addLegend,它将复制图形,正如我在帖子中提到的那样。 我希望这有帮助

set.seed(10)
library(MASS)
library(xts)

date=seq(as.Date("2000/1/1"), as.Date("2000/1/10"), "days")
matrixA=as.numeric(mvrnorm(n = 30, 0.5, 0.2, tol = 1e-6, empirical = TRUE, EISPACK = FALSE))
matrixA=matrix(matrixA,10,3)
martixA.ts=as.xts(matrixA,date)

matrixB=as.numeric(mvrnorm(n = 30, 0.5, 0.2, tol = 1e-6, empirical = TRUE, EISPACK = FALSE))
matrixB=matrix(matrixB,10,3)
martixB.ts=as.xts(matrixB,date)

par(mfrow=c(2,1))
plot(as.xts(matrixA,date),main="A")
#addLegend("bottomleft",legend.names = c("A","B"))
plot(as.xts(matrixB,date),main="B")
#addLegend("bottomleft",legend.names = c("",""))

你应该能够看到这个

enter image description here

答案 1 :(得分:0)

我对这个解决方案并不是特别满意,但它解决了当前的问题。

策略是在绘制/打印之前“完成”绘图完成。见下文。

set.seed(10)
library(MASS)
library(xts)

date <- seq(as.Date("2000-01-01"), as.Date("2000-01-10"), "days")
matrixA <- matrix(mvrnorm(n = 30, 0.5, 0.2, empirical = TRUE), 10, 3)
matrixA.ts <- xts(matrixA, date)

matrixB <- matrix(mvrnorm(n = 30, 0.5, 0.2, empirical = TRUE), 10, 3)
matrixB.ts <- xts(matrixB, date)

# Create the first plot, but do not draw it
# Assign the result to 'p1'
p1 <- plot(matrixA.ts, main = "A")
p1 <- addLegend("bottomleft", legend.names = c("A","B"))

# Create the second plot without drawing it
# Assign the result to 'p2'
p2 <- plot(matrixB.ts, main = "B")
p2 <- addLegend("bottomleft", legend.names = c("",""))

# Set up the device layout, and draw both plots
par(mfrow=c(2,1))
p1
p2