要在ggplot 中显示图例,您应该创建一个美学映射。最简单的方法是拥有一个单独的小数据框,其中包含您要在 hlines 上显示的信息。
您还没有提供任何示例数据,所以我在这里做了一些,以便这是一个完全可重现的示例:
library(ggplot2)
set.seed(69)
main_data <- data.frame(x = rnorm(200, 10), y = rnorm(200, 10))
hline_data <- data.frame(y = c(8, 10, 12), type = factor(c(2, 1, 2)),
stringsAsFactors = FALSE)
ggplot(main_data, aes(x,y)) +
geom_point() +
geom_hline(data = hline_data,
aes(yintercept = y, linetype = type, colour = type)) +
scale_colour_manual(values = c("blue", "red"),
labels = c("Recommended Spacing", "Limits of spacing"),
name = "Key") +
scale_linetype_manual(values = 1:2,
labels = c("Recommended Spacing", "Limits of spacing"),
name = "Key")
由reprex package (v0.3.0) 于 2020-05-19 创建