简体   繁体   中英

How to add x-axis labels to time series plots?

I have created a ts object for my data as below:

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  

However, when I plot the same, the plot is generated by shifting it before 2 months:

plot(sensor_test)

在此处输入图片说明

You've to work a bit with your data, then you can plot them:

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

Now you can plot it:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM