2011-04-20 94 views
3

我正在绘制一个软件版本到它发布的日期。例如:如何在X轴上放大日期?

test.cvs

Version,Date 
0.302,23/2/2011 
0.301,26/1/2011 
0.215,28/4/2010 
0.106,19/12/2008 
0.069,21/3/2008 

要绘制我使用:

tbl <- read.csv("test.csv") 
dates <-strptime(as.character(tbl$Date), "%d/%m/%Y") 
plot(dates,tbl$Version,type="o",main="Releases", xlab="Date",ylab="Version") 

它通过一年绘制它虽然,我宁愿希望按月/年绘制,并将标签垂直打印。我怎么能做到这一点?我尝试设置xaxt =“n”,并使用带有label = format(data,fmt)的axis()函数,但是我保持失败。

dput数据的片段:

structure(list(Version = c(0.302, 0.301, 0.215, 0.106, 0.069), 
    Date = structure(c(3L, 4L, 5L, 1L, 2L), .Label = c("19/12/2008", 
    "21/3/2008", "23/2/2011", "26/1/2011", "28/4/2010"), class = "factor")), .Names = c("Version", 
"Date"), class = "data.frame", row.names = c(NA, -5L)) 

回答

4

这里是一个基地图形版本。首先,它是更容易操作就地的Date列,而不是产生一个额外的dates对象:

tbl <- within(tbl, Date <- as.Date(Date, "%d/%m/%Y")) 

这则不会情节。请注意,我们需要在底部有一个多一点余量空间来容纳日期标签:

op <- par(mar = c(6,4,4,2) + 0.1) ## larger bottom margin 
## plot data but suppress axes and annotation 
plot(Version ~ Date, data = tbl, type = "o", axes = FALSE, ann = FALSE) 
## Use Axis to plot the Date axis, in 1 month increments 
## format the sequence of dates `ds` as abbreviated month name and Year 
with(tbl, Axis(Date, at = (ds <- seq(min(Date), max(Date), by = "months")), 
       side = 1, labels = format(ds, format = "%b %Y"), las = 2)) 
## Add y-axis and plot frame 
axis(2) 
box() 
## add on the axis labels 
title(ylab = "Version", main = "Releases") 
title(xlab = "Date", line = 5) ## pushing the x-axis label down a bit 
par(op) ## reset the pars 

这给我们:

plot with custom Date axis

更多的灵活性,可以通过改变我们想要日期的先后来获得在这里我们要每2个月,我们的标签将它们与2位世纪:

with(tbl, Axis(Date, at = (ds <- seq(min(Date), max(Date), by = "2 months")), 
       side = 1, labels = format(ds, format = "%b %y"), las = 2)) 

要使用此只是交换在上面呼叫地方现有的with(....)声明。

1

您可以轻松地做到这一点使用ggplot2。下面是一些代码

# generate data frame 
df = data.frame(
     Version = rnorm(20), 
     Date = seq(as.Date('2010-01-01'), by = '1 month', length = 20) 
    ) 

# create plot 
p0 = qplot(Date, Version, data = df) + 
    scale_x_date(major = '1 month') + 
    opts(axis.text.x = theme_text(angle = 90)) 

这里是输出

enter image description here

+0

我喜欢这个答案,因为它给出了网格并且很短,但我选择了另一个,因为它有很多我不知道的有用信息。谢谢你 – ForeverConfused 2011-04-20 18:30:06

2

为轴标签创建一个日期序列。

start <- as.Date("01/01/2008", "%d/%m/%Y") 
end <- as.Date("01/12/2011", "%d/%m/%Y") 
x_breaks <- seq(start, end, by = "month") 

创建dates作为Date以匹配上述序列。

dates <- as.Date(as.character(tbl$Date), "%d/%m/%Y") 

设置一些图形参数,可以las = 3旋转你的x轴; mar更改边距宽度。

par(las = 3, mar = c(7, 5, 3, 1)) 

现在绘制它,并按照您的建议手动添加x轴。

plot(dates,tbl$Version,type="o",main="Releases", xlab="", ylab="Version", xaxt = "n") 
axis(side = 1, at = as.numeric(x_breaks), labels = strftime(x_breaks, "%b %Y")) 
title(xlab = "Date", line = 5)