我正在用ggplot创建一个绘图,它使用彩色点,垂直线和水平线来显示数据 . 理想情况下,我想为 geom_vlinegeom_hline 层使用两种不同的颜色或线型比例,但ggplot不鼓励/禁止映射到相同美学的多个变量 .

# Create example data
library(tidyverse)
library(lubridate)
set.seed(1234)
example.df <- data_frame(dt = seq(ymd("2016-01-01"), ymd("2016-12-31"), by="1 day"),
                         value = rnorm(366),
                         grp = sample(LETTERS[1:3], 366, replace=TRUE))

date.lines <- data_frame(dt = ymd(c("2016-04-01", "2016-10-31")),
                         dt.label = c("April Fools'", "Halloween"))

value.lines <- data_frame(value = c(-1, 1),
                          value.label = c("Threshold 1", "Threshold 2"))

如果我为两个 geom_*line 设置线型美学,它们会被放在线型图例中,这不一定具有逻辑意义

ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
  geom_hline(data=value.lines, aes(yintercept=value, linetype=value.label)) +
  geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
  geom_point(size=1) +
  scale_x_date() + 
  theme_minimal()

或者,我可以将其中一条线设置为使用颜色美学,但之后再次将图例线条放入不合逻辑的图例分组中

ggplot(example.df, aes(x=dt, y=value, colour=grp)) +
  geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
  geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
  geom_point(size=1) +
  scale_x_date() + 
  theme_minimal()

我发现的唯一部分解决方案是在 geom_point 中使用填充美学而不是颜色,并设置 shape=21 以使用可填充的形状,但这会强制点周围出现黑色边框 . 我可以通过手动设置 color="white 摆脱边框,但随后白色边框覆盖了点 . 如果我设置 colour=NA ,则不会绘制点 .

ggplot(example.df, aes(x=dt, y=value, fill=grp)) +
  geom_hline(data=value.lines, aes(yintercept=value, colour=value.label)) +
  geom_vline(data=date.lines, aes(xintercept=as.numeric(dt), linetype=dt.label)) +
  geom_point(shape=21, size=2, colour="white") +
  scale_x_date() + 
  theme_minimal()

这可能是ggplot 's 1839235 rule can/should be broken, but I can'在它周围弄清楚方式的情况 . 使用填充 geom_point 表示最有希望,但没有办法删除点边框 .

在这里绘制两种不同颜色或线型美学的想法?