【问题标题】:R multiple plots of time series xts with only 1 legendR只有1个图例的时间序列xts的多个图
【发布时间】:2018-06-11 08:18:29
【问题描述】:

我想在不同的窗口中生成多个时间序列 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 的图 这里 否则,如果我把 addLegend 留在外面,这里的情节看起来像这样,

这是我想要的,但现在我只想添加一个图例。如果我为第一个和第二个图省略了命令 addLegend,则甚至没有绘制这些数字。 有人知道如何处理吗?提前谢谢你。

【问题讨论】:

  • 您能提供一个reproducible example吗?这将帮助我(和其他人)调试问题并提供解决方案。

标签: r xts


【解决方案1】:

给你。如果您取消注释 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("",""))

你应该能看到这个

【讨论】:

  • 这是对我的可重现示例评论的回复,还是对您问题的回答?
  • 这很好用,谢谢。还有一个问题,您如何禁用在图的右上角显示时间间隔?提前致谢。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多