Different legend-keys inside same legend in ggplot2

懵懂的女人 提交于 2019-11-27 14:40:53

You can use override.aes= inside guides() function to change default appearance of legend. In this case your guide is color= and then you should set shape=c(NA,16) to remove shape for line and then linetype=c(1,0) to remove line from point.

ggplot(df) +
  geom_line(aes(id, line, colour = "line")) +
  geom_point(aes(id, points, colour = "points"))+
  guides(color=guide_legend(override.aes=list(shape=c(NA,16),linetype=c(1,0))))

I am not aware of any way to do this easily, but you can do a hack version like this (using your melted dataframe):

p <- ggplot(df.m, aes(id, value)) +
  geom_line(aes(colour = variable, linetype = variable)) + scale_linetype_manual(values = c(1,0)) +
  geom_point(aes(colour = variable, alpha = variable)) + scale_alpha_manual(values = c(0,1))

The key is that you need to get the mapping right to have it displayed correctly in the legend. In this case, getting it 'right', means fooling it to look the way you want it to. It's probably worth pointing out this only works because you can set linetype to blank (0) and then use the alpha scale for the points. You can't use alpha for both, because it will only take one scale.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!