添加手动ggplot图例以实现功能组合

时间:2019-01-14 14:28:38

标签: r ggplot2 line legend

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

temp %>% gather("id","value",c(1,3,4)) %>% 
ggplot(aes(dt,value,col=id))+
geom_line(size=1.5)+scale_y_log10() +
xlim(1870, 2000)

这是一个传达想法的丑陋模型。标签的确切位置并不重要。我只希望每行一个图标。

enter image description here

这是我尝试实现的一种方法,但是图例因功能而爆炸,产生了六个图标,而不是三个:

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'

enter image description here

2 个答案:

答案 0 :(得分:1)

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

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

enter image description here

我增加了legend.key.width,否则看不到第二行类型是虚线。如果希望图例具有名称,请用它替换type,这样也可以删除所有NULL

答案 1 :(得分:0)

另一种解决方案是创建标签列,并使用geom_dl在图像中添加类似内容。

library(directlabels)
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))
)

D_legend$label<- case_when(
  D_legend$lwd==2 &D_legend$lty==1 ~ 'Litigating',
  D_legend$lwd==2 &D_legend$lty==2 ~ 'Non-litigating',
  D_legend$lwd==1 &D_legend$lty==1 ~ 'Reference')

ggplot(D_legend, aes(x=x, y=y, lty=lty, lwd=lwd, color=label)) + 
  geom_line(size=1) +
  theme_pvs_helvetica+
  scale_x_continuous(limits = c(0,12))+
  scale_color_manual(values =c('black','black','gray'))+
  theme(legend.position = 'none')+
  geom_dl(aes(x=x+0.1,label =label,color=label), method = 'last.points')

enter image description here