如何将 x 轴上的日期分配给 R 中的条形图?

How to assign dates on x-axis to the barplot in R?

我有多个日期数据集,我想使用 R 中的 barplot 函数绘制这些数据。数据是针对两个不同时期的,因此我希望在 x 轴上显示其各自的日期以便于比较。到目前为止,这是我的代码。 A_Date 用于 A 中的数据集,而 B_Date 用于 B 中包含的数据集。

A= runif(24, min = 25, max = 45)
B=runif(24, min = 35, max = 100)
DF=rbind(A,B)

A_Date= as.data.frame(seq(as.Date("1987-01-01"), to= as.Date("1988-12-31"),by="months"))
names(A_Date)= "Dates"
A_Date$year=as.numeric(format(A_Date$Dates, "%Y"))
A_Date$month=as.numeric(format(A_Date$Dates, "%m"))
A_Date=A_Date[,-1]
A_Date = as.character(paste(month.abb[A_Date$month], A_Date$year, sep = "_" ))

B_Date= as.data.frame(seq(as.Date("2010-01-01"), to= as.Date("2011-12-31"),by="months"))
names(B_Date)= "Dates"
B_Date$year=as.numeric(format(B_Date$Dates, "%Y"))
B_Date$month=as.numeric(format(B_Date$Dates, "%m"))
B_Date=B_Date[,-1]
B_Date = as.character(paste(month.abb[B_Date$month], B_Date$year, sep = "_" ))

barplot(DF, beside = T, col = c("red","darkblue"), legend.text =c("1987-88", "2010-11"), args.legend =list(x="topleft", cex = 1.2, bty="n", x.intersp=0.2),
        ylab = "Precipitation (mm)", cex.axis = 1.2, cex.lab=1.5)

此外,我想要 x 轴线(就像 y 轴上的线一样。 谢谢

我觉得很难将所有 4 个日期都放在轴上的一个位置。这是我能想到的最好的。我还重新排列了您的数据,使其适合一个数据框并使用了 ggplot2。

library(tidyverse)

new_df <- tibble(precip = runif(48, c(25, 25), c(45,100)),
                 dates = c(seq(as.Date("1987-01-01"), as.Date("1988-12-31"), by = "months"),
                           seq(as.Date("2010-01-01"), as.Date("2011-12-31"), by = "months")),
                 group = ifelse(lubridate::year(dates) %in% c(1987,1988), "1987-88", "2010-11"), 
                 month = lubridate::month(dates)) 

ggplot(new_df, aes(x = month, y = precip, fill = group)) + 
    geom_bar(stat = 'identity', position = position_dodge()) +
    scale_x_continuous(labels = paste0(1:12, "/1987 - 1988", "\n", 1:12, "/2010 - 2011"), 
                       breaks = 1:12) + 
    scale_fill_manual(values = c("red", "navy")) + 
    theme_classic() + 
    theme(legend.title = element_blank(), 
          axis.text = element_text(size = 10))

barplot也抛出一个坐标矩阵,我们可以通过赋值来捕获,这里是b <-。现在我们可以在正确的地方制作一个带有刻度的 axis。为了避免情节变得过于拥挤,我们可以统一多余的月份信息,将不同的年份拆分成 mtext 行。我这里用的是built-inmonth.abbs.

b <- barplot(DF, beside=T, col=c("red","darkblue"), 
             legend.text=c("1987-88", "2010-11"), 
             args.legend=list(x="topleft", cex=1.2, bty="n", x.intersp=0.2),
             ylab="Precipitation (mm)", cex.axis=1.2, cex.lab=1.5, ylim=c(0, 130))
axis(1, at=b[1, ], labels=FALSE)
axis(1, at=b[2, ], labels=FALSE)
mtext(rep(c(1987, 1988), each=12), 1, 1, at=b[1, ], cex=.8, las=2)
mtext(rep(c(2010, 2011), each=12), 1, 1, at=b[2, ], cex=.8, las=2)
mtext(rep(month.abb, 2), 1, 3, at=colMeans(b), las=2)

结果

如果您还想缩小 yx 轴之间的差距,您可以添加以下行:

abline(h=0, cex=1.3)