使用ggplot进行多年销售的同步X轴

时间:2015-11-20 17:36:11

标签: r ggplot2 synchronization time-series

我有从2012-01-01到现在(2015-11-20)的1417天销售数据。我无法弄清楚如何使用一年(1月1日 - 12月31日)轴和每年的销售额在同一个一年的窗口,即使使用ggplot' s { {1}}选项。

总销售额为color = as.factor(Year)

int

我已使用head(df$Total.Sales) [1] 495 699 911 846 824 949 包将Year从原始Day变量中拉出来。

lubridate

但因为Day包含年份信息

df$Day <- as.Date(as.numeric(df$Day), origin="1899-12-30") 
df$Year <- year(df$Day)

ggplot仍在绘制三年而不是将它们同步到同一时间段(一年,一年):

sample(df$Day, 1)
[1] "2012-05-05"

enter image description here

1 个答案:

答案 0 :(得分:1)

我创建了一些示例数据,如下所示

set.seed(1234)
dates <- seq(as.Date("2012-01-01"), as.Date("2015-11-20"), by = "1 day")
values <- sample(1:6000, size = length(dates))
data <- data.frame(date = dates, value = values)

顺便提一下,提供类似的东西是可重复的例子。

然后我准备一些额外的列

library(lubridate)
data$year <- year(data$date)
data$day_of_year <- as.Date(paste("2012",
                    month(data$date),mday(data$date), sep = "-"))

最后几行肯定是罗兰在评论中的意思。他选择闰年是正确的,因为它包含所有可能的日期。正常的一年将错过2月29日。

现在情节是由

生成的
library(ggplot2)
library(scales)
g <- ggplot(data, aes(x = day_of_year, y = value, color = as.factor(year))) +
   geom_line() + scale_x_date(labels = date_format("%m/%d"))

我打电话给scale_x_date来定义没有年份的x轴标签。这取决于包date_format中的函数scales。字符串"%m/%d"定义日期格式。如果您想了解有关这些格式字符串的更多信息,请使用?strptime

该图如下:

enter image description here

您可以立即看到此表示可能存在的问题。在这个情节上很难区分任何东西。但当然这也与我的样本数据差异很大的事实有关。您的数据可能看起来不同。否则,请考虑使用分面(请参阅?facet_grid?facet_wrap)。

相关问题