针对特定条件格式化 R 中的 X 轴标签

Formatting X axis label in R for a specific condition

对于以下示例代码:

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)

我有以下图表:

我想要的是当月份发生变化时,我希望能够在 x 轴上的日期下方添加月份名称。所以在这个例子中,当它变成01时,它应该显示01 Mar(单独一行的March)

如果你这样做,就会发生这种情况:

您的数据加上月份向量:

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

结果与您要求的一致: