如何在 R 中将天数数据绘制在月数据之上

How to plot days data on top of month data in R

提问人:user2954167 提问时间:11/17/2023 更新时间:11/18/2023 访问量:25

问:

我在 R 中有日期数据,其中列出了 11 个月的特定日期,如下所示(除了我有更多的数据点):

Intake.Date = c("2023-01-26", "2023-01-26", "2023-01-26", "2023-01-26", "2023-01-26",
"2023-01-26", "2023-01-26","2023-02-02", "2023-01-31", "2023-02-07", "2023-01-31",
"2023-02-16", "2023-02-18", "2023-02-18","2023-03-02", "2023-03-02", "2023-03-02",
"2023-03-06", "2023-03-06", "2023-03-06", "2023-03-08")

我想将图形分层 2:一个条形图,显示数据中每个月的计数,并在此基础上显示每天的计数。我从这个开始:

ggplot()+
geom_histogram(data = AFOBC_Pathology_Data, mapping = aes(Intake.Date), bins = 11)+
geom_bar(data = AFOBC_Pathology_Data, mapping = aes(Intake.Date), fill = 'cyan')

这将产生以下图形:在此处输入图像描述

这接近我想要的,但我知道垃圾箱(灰色条)不正确,因为我知道我每个月的日期数量不同。但是,如果我尝试将日期和月份映射到同一个图形上,如下所示:

ggplot()+
geom_bar(data = AFOBC_Pathology_Data, mapping = aes(format(Intake.Date,'%b')), fill = 'grey')+
geom_bar(data = AFOBC_Pathology_Data, mapping = aes(Intake.Date), fill = 'cyan'),

我收到以下错误:

中的错误: !无法转换为 . 运行以查看错误发生的位置。mapped_discrete()xrlang::last_trace()

r 日期 ggplot2 条形 直方图

评论


答:

1赞 stefan 11/17/2023 #1

第二种方法的问题在于,在第一种方法中,您映射了一个字符串,即月份缩写,又名离散变量 ,而在第二种方法中,它仍然是一个日期。geom_barx

如果您想让条形显示当月的计数,同时显示天数,我建议在外面手动计算计数并使用 ,例如ggplot()geom_rect

library(ggplot2)
library(dplyr, warn=FALSE)
library(lubridate)

AFOBC_Pathology_Data_binned <- AFOBC_Pathology_Data |> 
  mutate(
    month = format(Intake.Date, "%b")
  ) |> 
  summarise(
    start = floor_date(min(Intake.Date), "month"), 
    end = ceiling_date(max(Intake.Date), "month"),
    count = n(),
    .by = "month"
  )


ggplot(AFOBC_Pathology_Data) +
  geom_rect(
    data = AFOBC_Pathology_Data_binned,
    aes(
      xmin = start, xmax = end,
      ymin = 0, ymax = count
    ),
    fill = "grey"
  ) +
  geom_bar(
    aes(Intake.Date),
    fill = "cyan"
  )

在此处输入图像描述

数据

AFOBC_Pathology_Data <- data.frame(
  Intake.Date = c(
    "2023-01-26", "2023-01-26", "2023-01-26", "2023-01-26", "2023-01-26",
    "2023-01-26", "2023-01-26", "2023-02-02", "2023-01-31", "2023-02-07", "2023-01-31",
    "2023-02-16", "2023-02-18", "2023-02-18", "2023-03-02", "2023-03-02", "2023-03-02",
    "2023-03-06", "2023-03-06", "2023-03-06", "2023-03-08"
  )
)
AFOBC_Pathology_Data$Intake.Date <- as.Date(AFOBC_Pathology_Data$Intake.Date)

评论

0赞 user2954167 11/18/2023
谢谢!!我希望有一种更优雅的方式来管理它,但每次都比优雅更强大