带有月份和日期的时间序列日期在ggplot2中与facet一起绘制多年

MYa*_*208 12 r time-series ggplot2

我想有两个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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我尝试使用以下命令控制x轴标签

p + scale_y_continuous() + scale_x_date(labels = date_format("%d-%b"))
Run Code Online (Sandbox Code Playgroud)

但它会抛出以下错误消息.

Error: Invalid input: date_trans works with objects of class Date only
Run Code Online (Sandbox Code Playgroud)

Bri*_*ggs 21

你很近.您希望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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

可以使用适当的标签功能将轴格式化为更像日期,但仍然无法以日期识别方式找到中断.(除此之外,还有一个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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

为了获得漂亮的日期中断的好处,可以使用不同的变量.与原始数据具有相同日期的一年,但只有一年.在这种情况下,2000年是闰年.这个问题主要与闰日有关,但是如果你不关心这一点(非闰年的3月1日将与闰年的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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


inf*_*ner 6

坚持使用您的代码@ MYaseen208来创建数据.

当你绘制它时使用x = Date并使用下面的内容

p <- ggplot(data = df, aes(x = Date, y = Y, shape = Year, color = Year)) +
  geom_point() + geom_line(aes(group = 1))
  #adding facet and using facet_wrap with free x scales
  p <- p + facet_wrap(~Year,ncol=1, scales = "free_x") + theme_bw()+
scale_y_continuous() + 
scale_x_date(labels = date_format("%d-%b"), breaks = date_breaks("2 weeks")) +
 theme(axis.text.x = element_text(angle = 90, vjust = 0.5, size = 8))
Run Code Online (Sandbox Code Playgroud)

我用facet_wrap来获得免费的x_axis比例.当您将数据分开时,我们无法获得每年相同的日月组合.

在此输入图像描述