简体   繁体   中英

How to plot two simple time series of different lengths on same plot in R

I've got two simple time series data sets that I would like to plot on the same plot.

The trick is, the data sets are of different lengths and on totally different date ranges:

Data Set 1

|-----------|--------| 
| Date      | Visits | 
| 2/14/2013 | 1      | 
| 2/18/2013 | 3      | 
| 2/19/2013 | 1      | 
| 2/20/2013 | 12     | 
| 2/21/2013 | 10     | 
| 2/22/2013 | 11     |

Data Set 2

|----------|--------| 
| Date     | Visits | 
| 5/1/2015 | 19     | 
| 5/2/2015 | 4      | 
| 5/3/2015 | 10     | 
| 5/4/2015 | 27     | 
| 5/5/2015 | 12     | 
| 5/6/2015 | 6      | 
| 5/7/2015 | 1      | 
| 5/8/2015 | 4      |

I would like to scale them to the same range and make them date invariant such that I can plot them on the same plot, just to observe general trends (is there an increase of visits near the end or near the beginning etc).

I feel I must be missing a simple concept because I don't think this should be hard. Is this possible to do in R?

If your two time series exist as data.frames, you could approach it like

df1 <- data.frame(Date=c("2/14/2013",paste0("2/",as.character(18:22),"/2013")),Visits=c(1,3,1,12,10,11))
df2 <- data.frame(Date=paste0("5/",as.character(1:8),"/2015"),Visits=c(19,4,10,27,12,6,1,4))

# turn dates into Dates
df1$Date <- as.Date(df1$Date, format="%m/%d/%Y")
df2$Date <- as.Date(df2$Date, format="%m/%d/%Y")

This could be a quick way with a simple additive offset:

offset <- min(df2$Date) - min(df1$Date)   # this would make them start at the same place

df2.1 <- df2
df2.1$Date <- df2.1$Date - offset

plot(df1, xlim=range(c(df1$Date,df2.1$Date)),ylim=range(c(df1$Visits,df2$Visits)), type='l',col=2)
lines(df2.1,col=4)

Note that this is slightly annoying because the dates on the x-axis are only in terms of the first dataset. One hacky workaround is to convert them both to numeric.

df1$Date_n <- as.numeric(df1$Date)
df2$Date_n <- as.numeric(df2$Date)

...and perhaps have them both start at day 1.

df1$Date_n <- df1$Date_n - min(df1$Date_n) + 1
df2$Date_n <- df2$Date_n - min(df2$Date_n) + 1

Maybe include an offset and scale for plotting df2 with respect to df1

offset <- 0
scale <- 1
df2$Date_n1 <- df2$Date_n*scale + offset

plot(df1$Date_n, df1$Visits, type='l', col=2, xlim=range(c(df1$Date_n,df2$Date_n1)), ylim=range(c(df1$Visits,df2$Visits)), xlab="day", ylab="Visits")
lines(df2$Date_n1, df2$Visits, col=4)
legend("topleft", legend=c("series 1","series2"),lwd=1,col=c(2,4))

Perhaps not the most elegant of solutions, but it should get you there, hopefully with minimal tweaking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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