我一直在努力处理最后一部分代码,以使我正在工作的这张图真正为我和我的观众所用。我有一条带有两条线的条形图(一条充当滚动平均值,另一条充当该滚动平均值的峰值)。我要做的是一次用数字标记该峰线,但是在每个方面中每个方面的数字都不同。这是一些简化的数据和代码:
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轴时间的时间,并且每个构面都具有不同的日期。我可以肯定地确定它与日期有关,但是我不知道如何使文本块始终出现在每个面上。
答案 0 :(得分:0)
您只需要将其他数据集传递到仍保留构面变量的标签层。这将使用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
明确转换为日期/时间值才能使轴工作。