Dates appearing as decimals in R plot

久未见 提交于 2019-12-22 10:48:49

问题


I’m trying to plot some data with month data along the x-axis. Unfortunately the months are appearing as decimals. Any ideas?

library(zoo)  # Requires the zoo library.
theMonths <- as.yearmon(c( "Mar 2011", "Apr 2011", "May 2011", "Jun 2011", "Jul 2011", "Aug 2011", "Sep 2011", "Oct 2011", "Nov 2011", "Dec 2011", "Jan 2012", "Feb 2012"))
x <- c(1:12)
plot(theMonths,x,axes=FALSE)
axis(1,theMonths)
# Why do the dates appear on the axis as decimals?

回答1:


If you look at how the yearmon class objects are structured:

dput(theMonths)
structure(c(2011.16666666667, 2011.25, 2011.33333333333, 2011.41666666667, 
2011.5, 2011.58333333333, 2011.66666666667, 2011.75, 2011.83333333333, 
2011.91666666667, 2012, 2012.08333333333), class = "yearmon")

You can see that it stores these decimal values, and a call to as.numeric gives:

[1] 2011.167 2011.250 2011.333 2011.417 2011.500 2011.583 2011.667 2011.750 2011.833
[10] 2011.917 2012.000 2012.083

If you look at axis, the second argument is at and that is what you have called. When you don't specify labels it must take the at values as numerics. If you also specify labels the problem is solved:

axis(1,theMonths,theMonths)



回答2:


There is a bug in axis.yearmon which is fixed in the development version of zoo. Try this:

library(zoo)
source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/yearmon.R?revision=916&root=zoo")
z <- zooreg(1:12, as.yearmon("2011-03"), freq = 12)
plot(z, cex = .8)

ADDED: Since this question was answered zoo 1.7-7 has appeared on CRAN and it includes the above functionality so the development version is no longer needed.



来源:https://stackoverflow.com/questions/9178223/dates-appearing-as-decimals-in-r-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!