在共同的日月尺度上绘制不同的年份 [英] Plot separate years on a common day-month scale
问题描述
我想为 2012 年和 2013 年的夏天创建一个温度时间序列图.
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)
这是我目前使用 ggplot2
require(ggplot2)
ggplot(df, aes(date, temp, color=year))+
geom_point()
图表不需要在 x 轴上列出完整的日期,事实上,它可能应该只有月份和日期,这可能会解决问题,即
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")
我没有看到让 as.Date
或 as.POSIXct
(strptime
) 允许这种日月格式的方法.
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?
推荐答案
如果你的基础数据集是 temp 和 date,那么这就避免了对原始数据框的操作:
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(回应 OP 的评论).
EDIT (Response to OP's comment).
因此,这将上述方法与 Henrik 的方法结合起来,使用日期而不是 char 作为 x 轴,并避免修改原始 df.
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")
这篇关于在共同的日月尺度上绘制不同的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!