首页 > 解决方案 > 为功能组合添加手动 ggplot 图例

问题描述

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

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")

在此处输入图像描述

标签: rggplot2linelegend

解决方案


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

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.


推荐阅读