Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

r

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...).

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.

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.

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)
like image 234
daniele Avatar asked Oct 11 '13 09:10

daniele


1 Answers

To customize single panels in a multipanel plot is not thoroughly described in the actual ?plot.zoo text. 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.". 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.
Update. Thanks to @G. Grothendieck for an edit that made the code much cleaner!

# 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)

enter image description here

like image 114
Henrik Avatar answered Nov 04 '22 13:11

Henrik