我想有两个month
,并day
在使用的时间序列图的x轴facet
的年ggplot2
。我的MWE如下:
set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2014/1/1"), "week")
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)
df$Year <- format(df$Date, "%Y")
df$Month <- format(df$Date, "%b")
df$Day <- format(df$Date, "%d")
df$MonthDay <- format(df$Date, "%d-%b")
p <- ggplot(data=df, mapping=aes(x=MonthDay, y=Y, shape=Year, color=Year)) + geom_point() +geom_line(aes(group = 1))
p <- p + facet_grid(facets = Year ~ ., margins = FALSE) + theme_bw()
print(p)
我尝试使用以下命令控制x轴标签
p + scale_y_continuous() + scale_x_date(labels = date_format("%d-%b"))
但是它会引发以下错误消息。
Error: Invalid input: date_trans works with objects of class Date only
你很亲密 您希望x轴可以衡量您所在年份的位置,但是您可以将x轴用作字符向量,因此要标记每个点。如果改用连续变量表示这一点,则可能会有更好的结果。一个连续变量将是一年中的一天。
df$DayOfYear <- as.numeric(format(df$Date, "%j"))
ggplot(data = df,
mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
geom_point() +
geom_line() +
facet_grid(facets = Year ~ .) +
theme_bw()
可以使用适当的标签功能将轴格式化为更类似日期的格式,但是仍然无法以非常了解日期的方式找到中断。(最重要的是,还有一个NA
问题。)
ggplot(data = df,
mapping = aes(x = DayOfYear, y = Y, shape = Year, colour = Year)) +
geom_point() +
geom_line() +
facet_grid(facets = Year ~ .) +
scale_x_continuous(labels = function(x) format(as.Date(as.character(x), "%j"), "%d-%b")) +
theme_bw()
为了获得良好的日期间隔,可以使用其他变量。它与原始数据在同一天,但只有一年。在这种情况下,2000年是was年。与此相关的问题主要与leap日有关,但是如果您对此不关心(非-年的3月1日与a年的2月29日一致,等等),则可以使用:
df$CommonDate <- as.Date(paste0("2000-",format(df$Date, "%j")), "%Y-%j")
ggplot(data = df,
mapping = aes(x = CommonDate, y = Y, shape = Year, colour = Year)) +
geom_point() +
geom_line() +
facet_grid(facets = Year ~ .) +
scale_x_date(labels = function(x) format(x, "%d-%b")) +
theme_bw()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句