在 facet wrapped ggplot 的每个 facet 中为直线添加标签

Adding a label to a straight line in each facet of a facet wrapped ggplot

我一直在努力编写最后一点代码来使我正在处理的这张图真正适合我和我的观众。我有一个包含两条线的条形图(一条作为滚动平均值,另一条作为该滚动平均值的峰值)。我想要做的是用一个数字标记该峰值线,一次,但在每个方面的数字都不同的每个方面。这是一些精简的数据和代码:

tdf <- data.frame(a=as.POSIXct(c("2019-10-15 08:00:00","2019-10-15 09:00:00","2019-10-15 10:00:00","2019-10-15 08:00:00","2019-10-15 09:00:00","2019-10-15 10:00:00")),
                  b=as.Date(c("2019-09-02","2019-09-02","2019-09-02","2019-09-03","2019-09-03","2019-09-03")),
                  m1=c(0.2222222,0.3636364, 0.2307692, 0.4000000, 0.3428571, 0.3529412),
                  m2=c(0.2222222,0.2929293, 0.2972028, 0.3153846, 0.3714286, 0.3529412),
                  m3=c(0.2929293, 0.2929293, 0.2929293, 0.3529412,0.3529412,0.3529412))
 g <- ggplot(data = tdf, aes(x = a, y = m1)) +
  geom_bar(stat = "identity", alpha = 0.75, fill = 352) +
  xlab("time of day") +
  ylab("metric name") +
  ggtitle("Graph Title") +
  scale_x_datetime(breaks = scales::date_breaks("1 hours"), 
                   date_labels = "%H")+
  scale_y_continuous(breaks = c(0,.10,.20,.30,.40,.50,.50,.60,.70,.80,.90,1.0), 
                     labels = scales::percent) +
  theme_minimal()
# add line for m2
g <- g +
  geom_line(data = tdf, 
            aes(x = a, y = m2), 
            color = "blue", 
            size = 1.2)
# add line for m3
g <- g + geom_line(data=tdf, 
                   aes(x = a, y = m3), 
                   color = "#d95f02", 
                   size = 0.6, 
                   linetype = "dashed")
# last attempt to label the line results in an error: Invalid input: time_trans works with objects of class POSIXct
#g <- g+geom_text(aes(x=-Inf, y=Inf, label=median(tdf$m3)), size=2, hjust=-0.5, vjust= 1.4,inherit.aes=FALSE)
# facet wrap
g <- g + facet_wrap(~b, ncol = 5, scales = "fixed")

我见过一些技巧,但 none 似乎与在构面中的 x 轴有一个时间有关,并且每个构面都有不同的日期。我相当确定它与日期有关,但我有点不知道如何让文本块出现在每个方面。

您只需将不同的数据集传递到仍然保留分面变量的标签层。这将使用 dplyr

g <- g + 
  geom_text(data = tdf %>% 
              group_by(b) %>% 
              summarize(median = median(m3)), 
            aes(x = as.POSIXct(-Inf, origin="1970-01-01"), 
                y = Inf, 
                label = median), 
            size = 2,
            hjust = -0.5,
            vjust = 1.4, 
            inherit.aes = FALSE)

我们还必须明确地将 x 转换为 date/time 值才能使轴工作。