how to order the x-axis (in a graph) in chronological order?

▼魔方 西西 提交于 2020-12-12 01:59:07

问题


I create some fake (time series) data in R at daily intervals. I want to "aggregate" the data by "week", and then plot the data. I have posted my code below:

#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))

However, the x-axis for the graph does not appear to be in chronological order. The points seem to be "alternating" between 2014 and 2015.

Can someone please show me how to fix this?


回答1:


As @Allan mentioned it is easy if you keep dates as dates and use scale_x_date to format X-axis and specify their breaks the way you want.

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))



来源:https://stackoverflow.com/questions/65174250/how-to-order-the-x-axis-in-a-graph-in-chronological-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!