为特征组合添加手动 ggplot 图例

Add manual ggplot legend for combinations of features

如何为以下每一行添加带有标签的手动图例:

lty=1, lwd=2, color='black', label='Litigating'
lty=2, lwd=2, color='black', label='Non-litigating'
lty=1, lwd=1, color='gray', label='Reference'

这里有一个丑陋的模型来表达这个想法。标签的确切位置并不重要。我只想要每一行一个图标。

这是我尝试实现的一种方法,但图例按功能分解,产生六个图标而不是三个:

# Make a data.frame with 10 points and the aesthetics associated wit each
D_legend = data.frame(
  x = 1:10,
  y = rnorm(10),
  lwd = factor(c(2,2,2,2,2,2,1,1,1,1)),
  lty = factor(c(1,1,1,2,2,2,1,1,1,1)),
  color=c(rep('black', 6), rep('gray', 4))
)

# Plot it. I want a nice legend here!
ggplot(D_legend, aes(x=x, y=y, lty=lty, lwd=lwd, color=color)) + 
  geom_line() + 
  theme(legend.position="top")

让我们简单地创建一个确定行类型的交互变量:

D_legend$type <- droplevels(with(D_legend, interaction(lty, lwd, color)))
# Giving better names
levels(D_legend$type) <- c("Litigating", "Non-litigating", "Reference")

现在我们可以分别处理三种美学:

ggplot(D_legend, aes(x = x, y = y, lty = type, lwd = type, color = type)) + 
  geom_line() + theme(legend.key.width = unit(2, "cm")) +
  scale_linetype_manual(
    NULL, 
    values = c("Litigating" = 1, "Non-litigating" = 2, "Reference" = 1)
  ) +
  scale_size_manual(
    NULL, 
    values = c("Litigating" = 2, "Non-litigating" = 2, "Reference" = 1)
  ) +
  scale_color_manual(
    NULL, 
    values = c("Litigating" = "black", "Non-litigating" = "black", "Reference" = "gray")
  )

我增加了 legend.key.width 否则第二个线型是虚线是不可见的。如果你想让图例有名字,那么用它替换 type 这样你也可以删除所有 NULL.