簡體   English   中英

R:繪制時間序列時包括月份和年份

[英]R: Include both month and year when plotting time series

我的日期列為 type=Date

> class(df$Date)
[1] "Date"
> df$Date
  [1] "2010-10-01" "2010-11-01" "2010-12-01" "2011-01-01" "2011-02-01" "2011-03-01"
  [7] "2011-04-01" "2011-05-01" "2011-06-01" "2011-07-01" "2011-08-01" "2011-09-01"
 [13] "2011-10-01" "2011-11-01" "2011-12-01" "2012-01-01" "2012-02-01" "2012-03-01"
 [19] "2012-04-01" "2012-05-01" "2012-06-01" "2012-07-01" "2012-08-01" "2012-09-01"
 [25] "2012-10-01" "2012-11-01" "2012-12-01" "2013-01-01" "2013-02-01" "2013-03-01"
 [31] "2013-04-01" "2013-05-01" "2013-06-01" "2013-07-01" "2013-08-01" "2013-09-01"
 [37] "2013-10-01" "2013-11-01" "2013-12-01" "2014-01-01" "2014-02-01" "2014-03-01"
 [43] "2014-04-01" "2014-05-01" "2014-06-01" "2014-07-01" "2014-08-01" "2014-09-01"
 [49] "2014-10-01" "2014-11-01" "2014-12-01" "2015-01-01" "2015-02-01" "2015-03-01"
 [55] "2015-04-01" "2015-05-01" "2015-06-01" "2015-07-01" "2015-08-01" "2015-09-01"
 [61] "2015-10-01" "2015-11-01" "2015-12-01" "2016-01-01" "2016-02-01" "2016-03-01"
 [67] "2016-04-01" "2016-05-01" "2016-06-01" "2016-07-01" "2016-08-01" "2016-09-01"
 [73] "2016-10-01" "2016-11-01" "2016-12-01" "2017-01-01" "2017-02-01" "2017-03-01"
 [79] "2017-04-01" "2017-05-01" "2017-06-01" "2017-07-01" "2017-08-01" "2017-09-01"
 [85] "2017-10-01" "2017-11-01" "2017-12-01" "2018-01-01" "2018-02-01" "2018-03-01"
 [91] "2018-04-01" "2018-05-01" "2018-06-01" "2018-07-01" "2018-08-01" "2018-09-01"
 [97] "2018-10-01" "2018-11-01" "2018-12-01" "2019-01-01" "2019-02-01" "2019-03-01"
[103] "2019-04-01" "2019-05-01" "2019-06-01" "2019-07-01" "2019-08-01" "2019-09-01"
[109] "2019-10-01" "2019-11-01" "2019-12-01" "2020-01-01" "2020-02-01" "2020-03-01"
[115] "2020-04-01" "2020-05-01" "2020-06-01" "2020-07-01"

我正在嘗試通過執行以下操作將其設為 plot:

plot(x=df$Date, y=df$Feature, type="l")

但是,plot 僅在 x 軸上包含年份。 我希望它包括月份和年份,即格式為“%m%Y”。

我怎樣才能做到這一點?

這是一個使用ggplot package 的解決方案。

library(ggplot2)

# Transform the Date column to date format
ggplot(df, aes(x = as.Date(Date),
               y = Feature)) +
  # Draw line
  geom_line() +
  # Change x axis title
  labs(x = "Date (monthYear)") +
  # Set x breaks and the desired format for the date labels
  scale_x_date(date_breaks = "1 month", date_labels = "%m%Y")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM