r - 在 x 轴上绘制带有日期标签的时间序列

标签 r plot

我知道这个问题可能是陈词滥调,但我很难做到。

我的数据集采用以下格式:

    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" 之类的内容。 (下图)

screenshot

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/

相关文章:

删除 XML 包中 readHTMLTable 中的标签

r - 从嵌套列表中的所有矩阵中提取相同的列

在 pandas 中绘制毫秒范围

r - 在 R 中打印绘图时第一页为空

matlab - matlab极坐标图中的直线

n 个案例的 R Beautiful Colors

r - ggplot2 或plotly 中带有水平条形图的表格

R 如何取消shinyWidgets radioGroupButtons()中的悬停效果?

r - 如何在 R Markdown 输出中创建链接以获取带有文本超链接的 pdf 或 HTML

python - Matplotlib 条形图去除内部线条