2011-04-20 125 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)