如何在时间序列图上添加x轴标签?

时间:2019-12-20 08:30:44

标签: r time-series timeserieschart

我为数据创建了一个ts对象,如下所示:

sensor_test<-ts(Newdf_sorted$total_consumption,start = c(2018,04),end=c(2019,09),
                frequency = 12)
output:
  Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2018              59  65  70  83  62  98  63  95  57
2019  57  69  75  80  67  85  79  82 110  

但是,当我绘制相同的图时,会通过将其移动2个月之前生成图:

plot(sensor_test)

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要处理一些数据,然后才能绘制它们:

# random data, due you've not post any sample data
set.seed(1234)
sensor_test<-ts(round(rnorm(18,1,2),1),start = c(2018,04),end=c(2019,09),frequency = 12)

library(zoo)
# convert as data.frame and taking care of the dates
sensor_test_df <- data.frame(sensor_test = as.vector(sensor_test),
                             time = format(as.yearmon(time(sensor_test)),"%Y %m"))

现在您可以绘制它:

# the plot, you've to specify the type
plot(sensor_test_df$sensor_test, type = 'l', xaxt = "n")
# the axis labels
axis(1, at=1:18, labels=sensor_test_df$time)

enter image description here