Reputation: 591
Here is a reproducible example:
set.seed(55)
data <- rnorm(8)
date1 <- as.POSIXct("2018-06-18 10:30:00", tz = "CET") + 0:(length(data)/2-1)*60
date2 <- as.POSIXct("2019-03-28 10:30:00", tz = "CET") + 0:(length(data)/2-1)*60
dates <- append(date1, date2)
df1 <- xts(x = data[1:4], order.by = date1) %>%
fortify.zoo()
colnames(df1) <- c("Date1", "Data1")
df2 <- xts(x = data[5:8], order.by = date2) %>%
fortify.zoo()
colnames(df2) <- c("Date2", "Data2")
df <- cbind(df1, df2)
Output:
Date1 Data1 Date2 Data2
1 2018-06-18 10:30:00 0.1201391 2019-03-28 10:30:00 0.001908206
2 2018-06-18 10:31:00 -1.8123769 2019-03-28 10:31:00 1.188518494
3 2018-06-18 10:32:00 0.1515830 2019-03-28 10:32:00 -0.505343855
4 2018-06-18 10:33:00 -1.1192210 2019-03-28 10:33:00 -0.099234393
I am basically trying to plot Data1 and Data2 together in a same plot where the x axis are Date1 and Date2
My initial thought was to use reshape2::melt() but getting warnings like:
No id variables; using all as measure variables
attributes are not identical across measure variables; they will be dropped
Is there an easy way to do this? Thank you for your support.
Upvotes: 1
Views: 40
Reputation: 3388
With ggplot2
you can add two lines with different aesthetics for each:
ggplot(df) + geom_line(aes(Date1, Data1)) +
geom_line(aes(Date2, Data2), color='red')
Upvotes: 1
Reputation: 388982
You can get the data in long format, arrange
them according to Date
and then plot
library(tidyverse)
df %>%
pivot_longer(cols = names(.), names_to = c(".value", "temp"),
names_pattern = "(.*)(\\d)") %>%
arrange(Date) %>%
ggplot() + aes(Date, Data) + geom_line()
You can probably beautify the plot and add more details as needed.
Upvotes: 2