【问题标题】:How to add x-axis labels to time series plots?如何在时间序列图中添加 x 轴标签?
【发布时间】:2020-04-12 18:42:09
【问题描述】:

我为我的数据创建了一个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)

【问题讨论】:

    标签: r time-series timeserieschart


    【解决方案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)
    

    【讨论】:

    • 非常感谢,这行得通。我想了解为什么在创建 ts 对象后,它没有按提到的参数顺序绘制,比如 start(2018,04),所以很明显,理想情况下,绘图应该从 4 月开始,而不是 2 月。
    • 不客气!我假设因为plot() 将日期视为数字并仅使用它们来确定绘图顺序,但您必须指定标签。也许更有经验的用户可以添加一些更强有力的说明,我很乐意阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2021-11-16
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多