2016-09-25 72 views
0

我有一個數據框有兩個變量。其中一個是日期(Col1),另一個是數字人口數據(sk)。我可以繪製這樣的數據:如何在x軸中包含日期?

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 

你可以請幫助我如何前進嗎?

EDITCol1被該代碼定義:

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") 
+0

你可以給你的數據的一個例子嗎? 或先看到這篇文章:http://stackoverflow.com/questions/4843969/plotting-time-series-with-date-labels-on-x-axis –

+0

確保日期列是模式日期。如果不嘗試'as.Date(D $ Col1,format ='%Y-%m')'。格式可能不同 –

+0

'2013-01'將評估爲2012!需要用引號括起來,可能需要用'as.Date'作爲日期對象 –

回答

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) 

enter image description here

+0

您好,對於遲來的回覆感到抱歉。我安裝了動物園並按照你的建議提供了我的數據,一切都很順利,甚至可以繪圖,但是當我想在最後一行添加標籤時: 'DTs = zoo(D $ sk,D $ Col1) plot ,xaxt =「n」,xlab =「Date」,ylab =「pocet poberatelov」) 我得到以下錯誤: '錯誤在軸(邊,在= z,標籤=標籤,...): 情節。新還沒有被稱爲' 任何想法我做錯了什麼? – babesz

+0

我懂了!輸入plot(...)命令後,我不應該關閉圖形。然後axis.Date(...)只是將這些標籤添加到x軸。 – babesz