繁体   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