首页 > 解决方案 > ggplot2中的每月时间序列数据

问题描述

我想用下面的数据绘制每月时间序列,我得到了错误:

Invalid input: date_trans works with objects of class Date only* 

任何帮助都感激不尽。

下面是我的代码:

theme_set(theme_bw())
rdata1_m <- rdata1[1:36, ]
lbls <-paste0(month.abb[month(rdata1_m$date)], " ",lubridate::year(rdata1_m$date))
brks <- rdata1_m$date 
ggplot(rdata1_m, aes(x=date)) +geom_line(aes(y=GoldPrice)) +
scale_x_date(labels = lbls,breaks = brks) +
theme(axis.text.x = element_text(angle = 90, vjust=0.5),
panel.grid.minor = element_blank())

我的数据是:在此处输入图像描述

标签: rggplot2

解决方案


您的问题是日期列不是上课日期。用于lubridate更改日期然后绘图。date_labels此外,您可以使用和更轻松地设置中断和标签date_breaks

library(readr)
library(dplyr)
library(ggplot2)
library(lubridate)


rdata1 <- read_table2("date GoldPrice 
                                    2004-11-01 439.38 
                                    2004-12-01 442.08 
                                    2005-01-01 424.03 
                                    2005-02-01 423.35 
                                    2005-03-01 433.85 
                                    2005-04-01 429.23 
                                    2005-05-01 421.87 
                                    2005-06-01 430.66 
                                    2005-07-01 424.48 
                                    2005-08-01 437.93 
                                    2005-09-01 456.05 
                                    2005-10-01 469.9 
                                    2005-11-01 476.67 
                                    2005-12-01 510.1 
                                    2006-01-01 549.86 
                                    2006-02-01 555 
                                    2006-03-01 557.09 
                                    2006-04-01 610.65 
                                    2006-05-01 675.39 
                                    2006-06-01 596.15 
                                    2006-07-01 633.71 
                                    2006-08-01 632.59 
                                    2006-09-01 598.19 
                                    2006-10-01 585.78 
                                    2006-11-01 627.83 
                                    2006-12-01 629.79")

rdata1 %>%
  mutate(date = ymd(date)) %>%
  ggplot(aes(date, GoldPrice)) +
  geom_line() +
  scale_x_date(date_labels = "%b %Y", date_breaks = "1 month")+
  theme_bw()+
  theme(axis.text.x = element_text(angle = 90, vjust=0.5), 
        panel.grid.minor = element_blank())


推荐阅读