简体   繁体   English

R:绘制时间序列时包括月份和年份

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

I have my date column of type=Date我的日期列为 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"

I'm trying to plot it by doing the following:我正在尝试通过执行以下操作将其设为 plot:

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

However, the plot includes only the year on the x-axis.但是,plot 仅在 x 轴上包含年份。 I'd like it to include the month and the year, ie in format "%m%Y".我希望它包括月份和年份,即格式为“%m%Y”。

How can I achieve this?我怎样才能做到这一点?

Here is a solution using ggplot package.这是一个使用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