Last active
August 21, 2017 01:55
-
-
Save gdmcdonald/164e794a0d3ea4296cab0f30afee58f3 to your computer and use it in GitHub Desktop.
How to align the x-axis of two different time series plots in R, adapted from https://gist.github.com/boboppie/f115b2e1f0004a9d0623
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(grid) | |
library(lubridate) | |
# Create some data to play with. Two time series with offset timestamp. | |
df1 <- data.frame(DateTime = ymd("2010-07-01") + c(0:8760) * hours(2), series1 = rnorm(8761)) | |
df2 <- data.frame(DateTime = ymd("2011-07-01") + c(0:8760) * hours(2), series1 = rnorm(8761)) | |
# Create the two plots. | |
plotme <- function(inputdf,titletext,whatcolor){ | |
ggplot(inputdf, aes(x = DateTime, y = series1)) + | |
geom_point(size = 0.5, alpha = 0.75, color = whatcolor) + | |
ylab(titletext) + | |
theme_minimal()} | |
p1<-plotme(df1,"Red Dots","red")+ | |
theme(axis.title.x = element_blank())+ | |
ggtitle("Aligned DateTime X axes") | |
p2<-plotme(df2,"Blue Dots","blue")+ | |
xlab("Date") | |
#Get the limits of each plot | |
lim1<-ggplot_build(p1)$layout$panel_ranges[[1]]$x.range | |
lim2<-ggplot_build(p2)$layout$panel_ranges[[1]]$x.range | |
#find max/min | |
x_min<-as_datetime(min(c(lim1,lim2))) | |
x_max<-as_datetime(max(c(lim1,lim2))) | |
#rescale to be the new limits of both plots | |
p1 <- p1 + scale_x_datetime(limits=c(x_min, x_max)) | |
p2 <- p2 + scale_x_datetime(limits=c(x_min, x_max)) | |
#plot together | |
grid.newpage() | |
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment