我知道这个问题可能是陈词滥调,但我很难做到。
我的数据集采用以下格式:
Date Visits 11/1/2010 696537 11/2/2010 718748 11/3/2010 799355 11/4/2010 805800 11/5/2010 701262 11/6/2010 531579 11/7/2010 690068 11/8/2010 756947 11/9/2010 718757 11/10/2010 701768 11/11/2010 820113 11/12/2010 645259
I want to create a time-series plot, with x-axis representing time & y-axis vists. Also, I want to mark the x-axis with date. The code I was using is the following:
dm$newday = as.POSIXct(strptime(dm$Day, format="%Y-%m-%d"))
plot(as.Date(dm$day),dm$visits)
axis.Date(1,Day,at=seq(as.Date("2010/10/30"), as.Date("2011/01/29"),by="days"))
最佳答案
1) 由于时间是日期,请务必使用 "Date"
类,而不是 "POSIXct"
或 "POSIXlt “
。请参阅 R News 4/1 以获取建议,并在末尾的注释中定义了 Lines
的情况下尝试此操作。这里没有使用任何包。
dm <- read.table(text = Lines, header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)
使用 text = Lines
只是为了保持示例的独立性,实际上它会被替换为 "myfile.dat"
之类的内容。 (下图)
2) 由于这是一个时间序列,您可能希望使用时间序列表示形式,给出稍微简单的代码:
library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
plot(z, xaxt = "n")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)
根据您希望绘图的外观,在第一种情况下使用 plot(Visits ~ Date, dm)
或 plot(z)
可能就足够了> 在第二种情况下完全抑制 axis
命令。也可以使用 xyplot.zoo 来完成
library(lattice)
xyplot(z)
或autoplot.zoo:
library(ggplot2)
autoplot(z)
注意:
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
关于r - 在 x 轴上绘制带有日期标签的时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843969/