使用 POSIXct 类数据在 ggplots 中进行注释

我正在寻求帮助,为几何线图上同一 df 的 2 个数据子集注释或创建图例。困难似乎是因为我的 X 轴上有 POSIXct 数据。我发现了一个关于同一问题的问题,但没有明确的答案,可能还有一个尚未解决的错误 - How to use ggplot2's annotate with dates in x-axis?

我的图使用几周内收集的数据,根据到达病房的时间,总结了患者 (left.true) 在医院病房中花费的中位时间。花费的时间根据到达时间 (start.time) 和他们到达的病房区域 (INITIAL.AREA) 而有所不同,因此需要将其可视化为两条单独的线,但要跨时间绘制在一起以便客户理解 -因此有两个 geom_line 子集。

为不优雅的代码道歉,但创建情节 c 需要从 2 个向量之一到达时间,优先选择变量 Add.Time,除非它没有被记录(即 NA),在点它根据替代变量设置 start.time

los.plot <- ggplot() +
  geom_line(data = los2 %>%
              filter(INITIAL.AREA == "AMU") %>%
              mutate(start.time = case_when(
                !is.na(Adm.Time) ~ Adm.Time,is.na(Adm.Time) ~ Ward.Start.Time..in.Bed.)) %>%
              select(start.time,left.true) %>%
              group_by(start.time) %>%
              summarise(median = median(left.true)),aes(x=start.time,y=(median/60)),color = 'grey30') +
  geom_line(data = los2 %>%
              filter(INITIAL.AREA == "AAA") %>%
              mutate(start.time = case_when(
                !is.na(Adm.Time) ~ Adm.Time,y=(median / 60)),color='magenta') +
  labs(title = "Median LoS according to initial area of care",subtitle = "(Data from October 2019: n=1409)",#NAs removed
       caption = c("AEC patients","AMU Bedded patients"),x = "Time of arrival onto unit",y = "Median LoS (hours)") +
  theme(plot.caption = element_text(face = "bold",color = c('magenta','grey30'),hjust=c(1,0))) +
  scale_x_datetime(breaks = time.breaks,labels = c("00:00","02:00","04:00","06:00",'08:00','10:00','12:00','14:00','16:00','18:00','20:00','22:00','24:00'))

尝试使用注释

los.plot + annotate("text",x =03:00:00,y=1,label = "AEC patients",color = 'magenta')                 

导致

错误:无效输入:time_trans 仅适用于 POSIXct 类的对象

我假设这是因为 x 轴位置参数与 POSIXct 类不兼容。我似乎无法解决这个问题。

到目前为止,我唯一的解决方案是将 labs(captions = c(...,...) 作为向量,如主要代码所示,但如果没有清晰的图例或线条旁边的标签,您可以从图像中看到,这不是一个容易理解的图。我一直在努力尝试从头开始创建图例,因为我有两个不同的数据子集 - 但是,如果有人有解决这个的解决方案,它将避免所有 POSIX/x 轴困境。 >

使用 POSIXct 类数据在 ggplots 中进行注释

a119919756 回答:使用 POSIXct 类数据在 ggplots 中进行注释

仍然没有进一步提供注释和时间数据,但我确实发现了我在创建自己的图例时出错的地方 - 经过多次搜索找到了这篇文章:How to add a color legend to a ggplot with different geom layers

这说明要添加图例,我需要将颜色放入 aes()geom_line() 参数中,并使用 scale_fill_manual 设置颜色。

los.plot <- ggplot() +
  geom_line(data = los2 %>%
              ... (as above)
            aes(x=start.time,y=(median/60),color = "AMU Bedded")) +
  geom_line(data = los2 %>%
             ... (as above)
            aes(x=start.time,y=(median / 60),color="AEC")) +
  labs(title = ... (as above)) +
  scale_colour_manual(breaks = c("AMU Bedded","AEC"),values = c("grey30","magenta"))

我一直在设置 aes() 参数的外部颜色

现在给出: enter image description here

这正是我想要的

本文链接:https://www.f2er.com/408.html

大家都在问