我想用以下数据绘制每月的时间序列,但出现错误:
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())
答案 0 :(得分:2)
您的问题是,日期列不是上课日期。使用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())
答案 1 :(得分:0)
使用结尾处“注释”中可重复显示的数据,将其转换为具有yearmon
类索引的动物园时间序列对象。 yearmon
类代表每月数据,即包含年份和月份但不包含日期的日期。最后,将autoplot.zoo
与scale_x_yearmon
一起使用。如果您不喜欢默认值,请参见?scale_x_yearmon
以获取可用于自定义它的参数。
library(ggplot2)
library(zoo)
z <- read.zoo(rdata, FUN = as.yearmon)
autoplot(z) + scale_x_yearmon(format = "'%y/%m")
另一种可能性是转换为ts
对象,然后使用ggfortify中的autoplot.ts。使用z
和上面的库语句编写
library(ggfortify)
autoplot(as.ts(z))
Lines <- "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"
rdata <- read.table(text = Lines, header = TRUE)