【问题标题】:How to include dates in the x axis?如何在 x 轴中包含日期?
【发布时间】:2016-09-25 21:53:50
【问题描述】:

我有一个包含两个变量的数据框。其中一个是日期(Col1),另一个是数字人口数据(sk)。我可以像这样绘制数据:

plot(D$sk)

我的问题是(显然)该图不包括 x 轴中的日期。我试图通过这段代码添加它:

plot(D$sk, D$Col1, ylim=c(2013-01,2015-05))

但我收到一个空白图和以下错误消息:

Warning message:
In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion

基于this 对类似问题的回答,我尝试使用xaxt=n 参数,如下所示:

with(D, plot(Col1, sk, xaxt="n"))

但它也不起作用。我收到以下错误:

    Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

你能帮我怎么做吗?

编辑Col1 由以下代码定义:

Col1=seq(as.Date("2013/1/1"), by="1 month", length.out=41). 

sk 变量是介于 100.000 和 200.000 之间的某个随机数。对不起,但我是 R 新手,不知道如何重新处理。我从 41 张 excel 表中提取了它,并对其进行了几次转换。但基本上这些是数据框中的两个变量。我希望这会有所帮助。

EDIT2:抱歉,刚刚注意到还有另一个代码减少了日期变量:

D$Col1=format(D$Col1, format="%Y-%m")

【问题讨论】:

  • 你能举一个你的数据的例子吗?或者先看这个帖子:stackoverflow.com/questions/4843969/…
  • 确保日期列是模式日期。如果没有尝试 as.Date(D$Col1, format='%Y-%m') 。格式可能不同
  • 2013-01 将评估为 2012 年!需要用引号括起来,可能需要是带有as.Date的日期对象
  • 引号给出了这个错误:plot(D$sk, D$Col1, ylim=c("2013-01","2015-05")) Error in D$sk : $ operator is invalid for atomic vectors

标签: r date plot


【解决方案1】:

我建议使用zoo 包,它可以很容易地在 x 轴上绘制日期。这是一个例子

library(zoo)

IBM <- read.csv(paste0("http://real-chart.finance.yahoo.com/table.csv",
                       "?s=IBM&a=07&b=24&c=2010&d=07&e=24&f=2015",
                       "&g=d&ignore=.csv"))
IBM$Date <- as.Date(IBM$Date)
head(IBM)

# Date   Open   High    Low  Close   Volume Adj.Close
# 1 2015-08-24 143.47 147.76 143.00 143.47 10189700  138.1615
# 2 2015-08-21 151.50 153.19 148.70 148.85  7362100  143.3424
# 3 2015-08-20 152.74 153.91 152.50 152.66  4011500  147.0114
# 4 2015-08-19 155.15 155.67 153.41 153.94  4206400  148.2441
# 5 2015-08-18 155.51 156.52 155.25 156.01  2018300  150.2375
# 6 2015-08-17 155.20 156.69 154.70 156.31  2249600  150.5264

OpenPriceTs <- zoo(IBM$Open, IBM$Date)
plot(OpenPriceTs, xaxt="n", xlab="Date", ylab="Open Price")
axis.Date(1, at=IBM$Date, format="%b-%y", tcl=0)

【讨论】:

  • 您好,很抱歉迟来的回复。我安装了动物园并按照您的建议使用我的数据,一切正常,甚至绘图,但是当我想在最后一行添加标签时:DTs=zoo(D$sk, D$Col1) plot(DTs, xaxt="n", xlab="Date", ylab="pocet poberatelov") axis.Date(1, at=D$Col1, format="%b-%y", tcl=0) 我收到以下错误:Error in axis(side, at = z, labels = labels, ...) : plot.new has not been called yet 任何想法我在做什么错了吗?
  • 我明白了!输入 plot(...) 命令后,我不应该关闭图表。然后axis.Date(...)简单地将标签添加到x轴。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
相关资源
最近更新 更多