I want to create a time series plot of temperatures for the summers of 2012 and 2013.
The only problem is that I want the data series to plot one on top of the oth
If you want to plot both years in the same plot above each other then use dayMo
as your x values (they don't have to be date
object).
df$dayMo<-c("06-01", "07-01","08-01","09-01","06-01", "07-01","08-01","09-01")
ggplot(df, aes(dayMo, temp, color=year))+
geom_point()
If your base dataset is temp and date, then this avoids manipulating the original data frame:
ggplot(df) +
geom_point(aes(x=strftime(date,format="%m-%d"),
y=temp,
color=strftime(date,format="%Y")), size=3)+
scale_color_discrete(name="Year")+
labs(x="date")
EDIT (Response to OP's comment).
So this combines the approach above with Henrik's, using dates instead of char for the x-axis, and avoiding modification of the original df.
library(ggplot2)
ggplot(df) +
geom_point(aes(x=as.Date(paste(2014,strftime(date,format="%m-%d"),sep="-")),
y=temp,
color=strftime(date,format="%Y")), size=3)+
scale_color_discrete(name="Year")+
labs(x="date")
Another possibility is to create a fake date where a single year is concatenated with month and day from the original 'date'. An x variable of class Date
is easy to format with scale_x_date
. Load scales
package to access nice breaks and formatting functions: labels = date_format()
; breaks = date_breaks()
. See strptime
for other date formats.
library(scales)
df$date2 <- as.Date(paste(2014, format(date, "%m-%d"), sep = "-"))
ggplot(df, aes(date2, temp, color = year)) +
geom_point() +
scale_x_date(labels = date_format("%m/%d"))
ggplot(df, aes(date2, temp, color=year)) +
geom_point() +
scale_x_date(labels = date_format("%b-%d"),
breaks = date_breaks("months"))