Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

r - Plot separate years on a common day-month scale

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 other so they can be easily compared instead of sequentially along the date axis.

temp <- c(22, 22, 26, 23, 18, 20, 18, 17)
date <- as.Date(c("2012-06-01", "2012-07-01","2012-08-01","2012-09-01","2013-06-01","2013-07-01","2013-08-01","2013-09-01"))
year <- as.factor(c("2012", "2012", "2012", "2012","2013", "2013","2013","2013"))

df<- data.frame(temp, date, year)

Here's what I have so far using ggplot2

require(ggplot2)
ggplot(df, aes(date, temp, color=year))+
  geom_point()

The graph doesn't need to have the full dates listed on they x axis, in fact, it should probably just have month and day and that might solve the problem, i.e.

df$dayMo <- c("07-01", "07-02","07-03","07-04","07-01","07-02","07-03","07-04")

I didn't see a way to get as.Date or as.POSIXct (strptime) to allow this day-month format.

I'm also open to some other creative way of getting this done. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...