在x轴上用日期标签绘制时间序列 [英] Plotting time-series with Date labels on x-axis
问题描述
我知道这个问题可能是一个陈词滥调,但是我很难做到.
I know that this question might be a cliche, but I'm having hard time doing it.
我以以下格式设置了数据:
I've data set in the following format:
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
我想创建一个时间序列图,其中x轴表示时间& y轴拳头.另外,我想用日期标记x轴.我使用的代码如下:
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
的地方尝试此操作.这里没有使用任何软件包.
1) Since the times are dates be sure to use "Date"
class, not "POSIXct"
or "POSIXlt"
. See R News 4/1 for advice and try this where Lines
is defined in the Note at the end. No packages are used here.
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"
之类的东西代替. (图片后续)
The use of text = Lines
is just to keep the example self-contained and in reality it would be replaced with something like "myfile.dat"
. (continued after image)
2)由于这是一个时间序列,因此您可能希望使用时间序列表示形式来提供稍微简单一些的代码:
2) Since this is a time series you may wish to use a time series representation giving slightly simpler code:
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
命令就足够了.
Depending on what you want the plot to look like it may be sufficient just to use plot(Visits ~ Date, dm)
in the first case or plot(z)
in the second case suppressing the axis
command entirely.
注意:
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"
这篇关于在x轴上用日期标签绘制时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!