time series plot with x axis in “year”-“month” in R

后端 未结 3 704
我寻月下人不归
我寻月下人不归 2020-12-03 05:27

I have a \"monthly data\" I want to plot the data such that I get a date in the format %Y-%m\" (2001-01) on the x-axis. Say my data is pcp <- rnorm(24

3条回答
  •  情书的邮戳
    2020-12-03 06:07

    Here's an idea with toy data since the question is not reproducible. Hopefully it helps

    R> foo = ts(rnorm(36), frequency = 12, start = 2001)
    R> plot(foo, xaxt = "n")
    R> tsp = attributes(foo)$tsp
    R> dates = seq(as.Date("2001-01-01"), by = "month", along = foo)
    R> axis(1, at = seq(tsp[1], tsp[2], along = foo), labels = format(dates, "%Y-%m"))
    

    Output

    ggplot version with data that looks like yours

    R> df = data.frame(date = seq(as.POSIXct("2001-01-01"), by = "month", length.out = 36), pcp = rnorm(36))
    R> library(ggplot2)
    R> library(scales)
    R> p = ggplot(data = df, aes(x = date, y = pcp)) + geom_line()
    R> p + scale_x_datetime(labels = date_format("%Y-%m"), breaks = date_breaks("months")) + theme(axis.text.x = element_text(angle = 45))
    

    enter image description here

提交回复
热议问题