2015-03-13 136 views
5

對於以下示例代碼:中的R格式化X軸標籤的特定條件

y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31) 
days <- seq(as.Date("2015-2-25"), by="day", length=11) 
n <- length(y) 
x <- 1:n 
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n') 
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1) 
lines(y) 

我有以下圖表:

enter image description here

當月變化我想是,我希望能夠在x軸的下方添加月份名稱。因此,在這個例子中,當它變成01,應該(在單獨的一行月)顯示03月01

回答

2

,如果你做這樣的事它可以發生:

你的數據加上一個月向量:

y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31) 
days <- seq(as.Date("2015-2-25"), by="day", length=11) 

#my addition 
#contains the name of the month for where day == '01' else is blank 
months <- ifelse(format(days, '%d')=='01', months(days) , '') 

n <- length(y) 
x <- 1:n 

解決方案:

plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n') 
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1) 
lines(y) 

到這裏只有你的代碼。現在,你需要添加一個新的軸,設置軸顏色爲白色,繪製在上面創建的載體一個月:

par(new=T)   #new plot 
par(mar=c(4,4,4,2)) #set the margins. Original are 5,4,4,2. 
#I only changed the bottom margin i.e. the first number from 5 to 4 

#plot the new axis as blank (colour = 'white') 
axis(1, at=seq(1,11) ,labels=months, las=1, col='white') 

結果看起來你問什麼:

enter image description here