在基本 R plot() 中自动显示时间序列的日期结构的方法
Automated way of displaying the date structure of a time series in basic R plot()
install.packages('RCurl')
require(RCurl)
install.packages('zoo')
require(zoo)
x = getURL("https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv")
soccer <- read.csv(textConnection(x), header=T)
s <- zoo(soccer)
plot.ts(s$soccer_US)
结果
但我需要 x 轴作为日期。
我知道有很多关于同一主题的帖子,尽管其中很多——包括我可能已经发布的一些——需要 xaxt="n"
,这似乎是一种非常迂回的方式.
有没有更简单的方法来保留 basic 中 x 轴的日期结构plot()
?
题目代码中zoo(...)命令使用不当。请参阅 ?zoo 以获取有关它的信息。
为此,使用 yearmon class 将文件读入动物园对象 z,然后使用 plot 或 autoplot。
library(zoo)
u <- "https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv"
z <- read.csv.zoo(u, FUN = as.yearmon)
plot(z)
或将最后一行替换为:
library(ggplot2)
autoplot(z) + scale_x_yearmon()
备注
文件的前几行如下所示:
L <- readLines(u)
writeLines(head(L))
给予:
date,count
2004-01,25
2004-02,29
2004-03,33
2004-04,36
2004-05,37
接受的答案确实使用了 zoo
,就像在 OP 中一样。但是,我的首选方法是尽可能避免使用包(如评论中所述)。以下工作方式符合我的预期:
require(RCurl)
x = getURL("https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv")
dat <- read.csv(textConnection(x))
dat$date <- as.Date(paste(dat$date,"-01",sep=""), format="%Y-%m-%d")
plot(dat, type='l', xaxt='n', lwd=3, col='firebrick', xlab='', ylab='')
at1 <- seq(min(dat$date), max(dat$date)+10, by="3 months")
axis.Date(1, at=at1, format="%b %d", las=2, cex.axis=0.7)
这是 运行 在 Google Colab 上的这段代码的屏幕截图:
install.packages('RCurl')
require(RCurl)
install.packages('zoo')
require(zoo)
x = getURL("https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv")
soccer <- read.csv(textConnection(x), header=T)
s <- zoo(soccer)
plot.ts(s$soccer_US)
结果
但我需要 x 轴作为日期。
我知道有很多关于同一主题的帖子,尽管其中很多——包括我可能已经发布的一些——需要 xaxt="n"
,这似乎是一种非常迂回的方式.
有没有更简单的方法来保留 basic 中 x 轴的日期结构plot()
?
题目代码中zoo(...)命令使用不当。请参阅 ?zoo 以获取有关它的信息。
为此,使用 yearmon class 将文件读入动物园对象 z,然后使用 plot 或 autoplot。
library(zoo)
u <- "https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv"
z <- read.csv.zoo(u, FUN = as.yearmon)
plot(z)
或将最后一行替换为:
library(ggplot2)
autoplot(z) + scale_x_yearmon()
备注
文件的前几行如下所示:
L <- readLines(u)
writeLines(head(L))
给予:
date,count
2004-01,25
2004-02,29
2004-03,33
2004-04,36
2004-05,37
接受的答案确实使用了 zoo
,就像在 OP 中一样。但是,我的首选方法是尽可能避免使用包(如评论中所述)。以下工作方式符合我的预期:
require(RCurl)
x = getURL("https://raw.githubusercontent.com/RInterested/DATASETS/gh-pages/interest%20in%20soccer%20in%20the%20US.csv")
dat <- read.csv(textConnection(x))
dat$date <- as.Date(paste(dat$date,"-01",sep=""), format="%Y-%m-%d")
plot(dat, type='l', xaxt='n', lwd=3, col='firebrick', xlab='', ylab='')
at1 <- seq(min(dat$date), max(dat$date)+10, by="3 months")
axis.Date(1, at=at1, format="%b %d", las=2, cex.axis=0.7)
这是 运行 在 Google Colab 上的这段代码的屏幕截图: