我想在 geom_hline 中为我的水平线创建一个图例。我使用的数据来自 3 个不同的数据框。我也在使用gghighlight,我相信它掩盖了任何传说。在这种情况下我如何强制传奇?
这 3 个数据帧是:1)“数据集”,它存储所有点的值 2)“限制”,其中包含某些参数的最大值、最小值和目标 3)“平均值”,它包含每个参数的平均值。
以下是数据集的最小可重现样本:
dataset <- data.frame(
param = c('A','A','A','A','A', 'T','T','T','T','T', 'N','N','N','N','N', 'R','R','R','R','R'),
category = c('Other','this','Other','Other','Other','this','Other','Other','Other','Other','Other','Other','this','Other','Other','Other','Other','Other','Other','this'),
average = c(1.55,1.46,1.42,1.57,1.58, 1.57,1.46,1.42,1.57,1.59, 1.67,1.56,1.62,1.67,1.69, 1.47,1.36,1.32,1.47,1.49),
datetime = c('2019-06-10 07:27:24','2019-06-10 08:20:24','2019-06-10 09:27:24','2019-06-10 07:45:24','2019-06-10 08:13:24',
'2019-06-10 09:27:24','2019-06-10 10:20:24','2019-06-10 11:27:24','2019-06-10 09:45:24','2019-06-10 10:13:24',
'2019-06-10 13:27:24','2019-06-10 14:20:24','2019-06-10 15:27:24','2019-06-10 13:45:24','2019-06-10 14:13:24',
'2019-06-10 18:27:24','2019-06-10 19:20:24','2019-06-10 20:27:24','2019-06-10 18:45:24','2019-06-10 19:13:24')
)
dataset$datetime <- as.POSIXct(dataset$datetime, format = "%Y-%m-%d %H:%M:%S")
limits <- data.frame(
param = c('A', 'T'),
target = c(1.55, 1.55),
min = c(1.39, 1.39),
max = c(1.71, 1.71)
)
mean <- data.frame(
param = c('A', 'T', 'N', 'R'),
mean = c(1.549, 1.548, 1.65, 1.45)
)
这是我的代码:
library(ggplot2)
library(gghighlight)
ggplot(data=dataset, mapping=aes(x=datetime, y=average)) +
geom_line(group=1, alpha=0.3, color='black') +
geom_hline(data=limits, mapping=aes(yintercept = max), color='red', linetype='dashed') + #max line
geom_hline(data=limits, mapping=aes(yintercept = min), color='red', linetype='dashed') + #min line
geom_hline(data=limits, mapping=aes(yintercept = target), color='blue', linetype='dashed') + #target line
geom_hline(data=mean, mapping=aes(yintercept = mean), color='green', linetype='dashed') + #mean line
geom_point(size=2, color='red') +
facet_wrap(param~., scales='free') +
gghighlight(category!='Other', label_key = average, n=1, use_group_by = FALSE,
unhighlighted_params = list(color='black', size=1, alpha=0.7)) +
labs(x='Time' , y='Value') +
theme_bw()
图例应显示:“红色”:最小/最大,“蓝色”:目标,“绿色”:平均值。谢谢!