简体   繁体   English

如何在多个plot.zoo中添加多条直线

[英]How to add multiple straight lines in a multi plot.zoo

I have multiple time series data plots and I need an horizontal line in each plot but with different horizontal values (es. 1st plot: h=50 , 2nd plot: h=48 ...). 我有多个时间序列数据图,我需要在每个图中有一条水平线,但水平值不同(例如,第一个图: h=50 ,第二个图: h=48 ......)。

I tried abline(h=50... and I get the horizontal line in each plot. I tried abline(h=c(50,48... and I get multilple horizontal lines in each plot. 我尝试了abline(h=50...我得到了每个图中的水平线。我尝试了abline(h=c(50,48...我在每个图中得到多条水平线。

I can't figure out how to get the plot.zoo index in order to plot h=50 in the 1st plot, h=48 in the 2nd plot and so on. 我无法弄清楚如何获得plot.zoo指数以便在第一个图中绘制h=50 ,在第二个图中h=48 ,依此类推。

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)

# plot with single line
my.panel <- function(x, ...) {
    lines(x, ...)
    abline(h=50, col = "red", lty="solid", lwd=1.5 )
}
plot.zoo(x, main="title",
plot.type="multiple", type="o", lwd=1.5, col="blue",
panel=my.panel)


# plot multiple lines in all plots
my.panel <- function(x, ...) {
    lines(x, ...)
    abline(h=c(50,50,48,50), col = "red", lty="solid", lwd=1.5 )}

plot.zoo(x, main="title",
plot.type="multiple", type="o", lwd=1.5, col="blue",
panel=my.panel)

To customize single panels in a multipanel plot is not thoroughly described in the actual ?plot.zoo text. 在实际的?plot.zoo文本中没有详细描述在多面板图中自定义单个面板。 In the 'Details' section you find: 在“详细信息”部分中,您会发现:
"In the case of a custom panel the panel can reference parent.frame$panel.number in order to determine which frame the panel is being called from. See examples.". “在自定义面板的情况下, panel可以引用parent.frame$panel.number以确定从哪个帧调用面板。参见示例。” And there are quite a few examples. 还有很多例子。 Using them as template, I found that this could be a way to call separate panels, and draw a separate hline in each. 使用它们作为模板,我发现这可以是一种调用单独面板的方法,并在每个面板中绘制一个单独的hline
Update. 更新。 Thanks to @G. 感谢@G。 Grothendieck for an edit that made the code much cleaner! Grothendieck进行编辑,使代码清晰!

# create values for hline, one for each panel
hlines <- c(50, 50, 48, 50)

# panel function that loops over panels
my.panel <- function(x, ...) {
  lines(x, ...)
  panel.number <- parent.frame()$panel.number
  abline(h = hlines[panel.number], col = "red", lty = "solid", lwd = 1.5)
}

plot.zoo(x, main = "title", type = "o", lwd = 1.5, col = "blue", panel = my.panel)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM