簡體   English   中英

將 label 添加到分面包裝 ggplot 的每個方面的直線上

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

我一直在努力編寫最后一點代碼,以使我正在制作的這張圖表真正為我和我的觀眾工作。 我有一個帶有兩條線的條形圖(一條用作滾動平均線,另一條用作滾動平均線的峰值)。 我想要做的是 label 那個峰值線與一個數字,一次,但在每個方面,每個方面的數字都不同。 這是一些精簡的數據和代碼:

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")

我見過一些技術,但它們似乎都沒有涉及在刻面中為 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顯式轉換為日期/時間值才能使軸工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM