R: how to plot a “time series” with ggplot2

只谈情不闲聊 提交于 2021-01-07 02:39:04

问题


I simulated some time series data in R, aggregated by every 8 days, and then tried to plot the results. However, the plots are not working. I have posted my code below:

#load library
library(xts)
library(ggplot2)

set.seed(123)
    
#simulate data
    property_damages_in_dollars <- rnorm(731,100,10)

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")
    
final_data <- data.frame(date_decision_made, property_damages_in_dollars)

#convert to xts object
dat <- xts(final_data$property_damages_in_dollars, 
           as.Date(final_data$date_decision_made, '%Y/%m/%d'))

#aggregate by 8 day period
ep <- endpoints(dat,'days',k=8)

a = period.apply(x=dat,ep,FUN=sum )

#plot : does not work
plot(a)

#plot using ggplot :does not work

ggplot(a, aes(x = a[,1], y=a$a))+
         geom_line(aes(group=1))+
  scale_x_discrete(guide = guide_axis(n.dodge=2))+
  theme(axis.text.x = element_text(angle = 45))

Could someone please tell me what I am doing wrong?

Thanks


回答1:


autoplot(a, geom = "point")

Autoplot seems to work. More info here.



来源:https://stackoverflow.com/questions/65164596/r-how-to-plot-a-time-series-with-ggplot2

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