如何在日期时放大X轴?

时间:2011-04-20 15:45:24

标签: r

我正在将软件版本绘制到发布日期。例如:

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()函数,但我一直都失败了。

数据摘录:

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))

3 个答案:

答案 0 :(得分: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 :(得分: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)

答案 2 :(得分: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