2015-03-13 58 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