I am trying to add vertical lines to a time series plot I made in base R plot(data1,type = 'l',lwd = 1.5, family = "A", ylab ="", xlab = "", main = "")
. This plot has a total of 5 plots inside of it. There are two x-axes that are the same (see current plot)
When adding vlines with abline(v=c(27,87, 167, 220, 280, 329), lty=2)
I get this result
Is there a way to get them to go on the graphs so it looks something like this but with dashed lines and the lines within the plots.
Or if you know of a better way to plot this in ggplot that would be fantastic as well. Thank you so much in advance.
CodePudding user response:
Here is a toy example of using ggplot to put in vlines.
library(tidyverse)
iris2 <- iris %>% pivot_longer(cols=Sepal.Length:Petal.Length)
ggplot(iris2, aes(x = Petal.Width, y = value))
geom_line()
facet_wrap(~name, scales="free_y", ncol=2)
geom_vline(xintercept=c(.25, .75, 1.25, 1.75, 2.25),
linetype='dashed', col = 'blue')
CodePudding user response:
plot
calls plot.ts
. This has a panel=
argument in which you may define a function what should happen in the panels. Since you want a grid
and the usual lines
, you can do quite easily:
panel <- function(...) {grid(col=1, ny=NA, lty=1); lines(...)}
plot(z, panel=panel)
grid
usually uses the axTicks
and you can define number of cells, see ?grid
.
This also works with abline
.
panel <- function(...) {abline(v=seq(1961, 1969, 2), col=1,lty=1); lines(...)}
plot(z, panel=panel)
Data:
set.seed(42)
z <- ts(matrix(rnorm(300), 100, 5), start = c(1961, 1), frequency = 12)