如何在 R 中将月份从数字(ex.month 1,月份 1)更改为名称(例如 Jan,Feb)?

How do I change months from numeric (ex.month 1,month 1) to name (ex. Jan,Feb) in R?

我无法将 x 轴中的月份从数字更改为名称(参见图片)。下面是我的代码。我想将 x 轴上的月份 (1,2,3,4,..) 更改为 (Jan,Feb,Mar,...)。

dd <- data.frame(beginning=c(6,6,6,7,7,8),
                 end=c(7,7,7,7,7,12),
                 solution=c("death", "death","death","death","death","recovered")
)
dd$id <- c(1:length(dd[,1]))
par(mfcol=c(1,1), mar=c(5,5,1.6,1),cex.lab=1)
plot(id~beginning, data=dd,
     xlim=c(1,12), ylim=c(0, max(dd$id)+2),# axis limits
     pch=NA, # dont plot points yet
     yaxt="n", xaxt="n", 
     xlab="Month", ylab="Case No.")
axis(side=2, at=dd$id, labels=dd$id, las=1)
axis(side=1,
     at=seq(1,12, by=1),
     labels=seq(1,12, by=1))
with(dd, arrows(y0=id, x0=beginning, y1=id, x1=end, length = 0))
with(dd, points(beginning, id, pch=25, bg="red", cex=1.5))
dd$my.pch <- ifelse(dd$solution=="recovered",24,4)
with(dd, points(end, id, pch= my.pch, bg="green", cex=1.5))
legend("topleft", legend=c("ill", "recovered", "death"),
       pch=c(25,24,4),
       pt.bg= c("red", "green", "black"),
       bty="n"
)

您只需要对代码进行非常小的更改。

labels=seq(1,12, by=1) 替换为全名 labels=month.name 或缩写名称 labels=month.abb

dd <- data.frame(beginning=c(6,6,6,7,7,8),
                 end=c(7,7,7,7,7,12),
                 solution=c("death", "death","death","death","death","recovered")
)


dd$id <- c(1:length(dd[,1]))
par(mfcol=c(1,1), mar=c(5,5,1.6,1),cex.lab=1)
plot(id~beginning, data=dd,
     xlim=c(1,12), ylim=c(0, max(dd$id)+2),# axis limits
     pch=NA, # dont plot points yet
     yaxt="n", xaxt="n", 
     xlab="Month", ylab="Case No.")
axis(side=2, at=dd$id, labels=dd$id, las=1)
axis(side=1,
     at=seq(1,12, by=1),
     labels=month.abb)
with(dd, arrows(y0=id, x0=beginning, y1=id, x1=end, length = 0))
with(dd, points(beginning, id, pch=25, bg="red", cex=1.5))
dd$my.pch <- ifelse(dd$solution=="recovered",24,4)
with(dd, points(end, id, pch= my.pch, bg="green", cex=1.5))
legend("topleft", legend=c("ill", "recovered", "death"),
       pch=c(25,24,4),
       pt.bg= c("red", "green", "black"),
       bty="n"
)

给出: