问题
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