【问题标题】:how to order the x-axis (in a graph) in chronological order?如何按时间顺序排列 x 轴(在图表中)?
【发布时间】:2021-03-18 07:38:03
【问题描述】:

我每天在 R 中创建一些假的(时间序列)数据。我想按“周”“聚合”数据,然后绘制数据。我在下面发布了我的代码:

#set seed
set.seed(123)

#load libraries
library(xts)
library(ggplot2)

#create data

date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,100,10)

final_data <- data.frame(date_decision_made, property_damages_in_dollars)



#aggregate
y.mon<-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
                                                    format="%W-%y"),data=final_data, FUN=sum)

y.mon$week = y.mon$`format(as.Date(date_decision_made), format = "%W-%y")`

#Plot
ggplot(y.mon, aes(x = week, y=property_damages_in_dollars))+
         geom_line(aes(group=1))+
  scale_x_discrete(guide = guide_axis(n.dodge=2))+
  theme(axis.text.x = element_text(angle = 45))

但是,图表的 x 轴似乎没有按时间顺序排列。这些点似乎在 2014 年和 2015 年之间“交替”。

谁能告诉我如何解决这个问题?

【问题讨论】:

  • 将您的 x 值保存为日期对象。更改 scale_x_dates 中标签的格式,而不是在您的数据中这样做,否则 ggplot 会将它们视为因子并按字母顺序绘制。

标签: r ggplot2 time-series aggregate data-visualization


【解决方案1】:

正如@Allan 所说,如果您将日期保留为日期并使用scale_x_date 格式化 X 轴并按照您想要的方式指定它们的中断,这很容易。

library(dplyr)
library(ggplot2)

final_data %>%
  mutate(date_decision_made = as.Date(date_decision_made, "%Y/%m/%d"),
         week = format(date_decision_made, "%W-%y")) %>%
  group_by(week) %>%
  summarise(property_damages_in_dollars = sum(property_damages_in_dollars), 
            date = first(date_decision_made)) %>%
  ggplot() + aes(x = date, y=property_damages_in_dollars) + 
  geom_line(aes(group=1)) +
  scale_x_date(date_labels = "%W-%y", date_breaks = '1 month') + 
  theme(axis.text.x = element_text(angle = 45))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多