对于以下示例代码:
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)
Run Code Online (Sandbox Code Playgroud)
我有以下图表:

我想要的是当月份发生变化时,我希望能够在x轴上添加月份名称.所以在这个例子中,当它变成01时,它应该显示01月3日(3月在一个单独的行上)
如果您执行以下操作,则可能会发生这种情况:
您的数据加上月份向量:
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
Run Code Online (Sandbox Code Playgroud)
解决方案:
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)
Run Code Online (Sandbox Code Playgroud)
到目前为止,只有您的代码。现在您需要添加一个新轴,将轴颜色设置为白色并绘制上面创建的月份向量:
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')
Run Code Online (Sandbox Code Playgroud)
结果看起来像你所要求的:
