在ggplot2中修改图例标题遇重复图例问题求助
解决ggplot图例标题重复问题
问题原因
你在代码中同时将color、shape、linetype三个美学属性绑定到了sSkills变量,但仅在labs()中修改了color的标题,shape和linetype的标题仍为默认的sSkills。ggplot会将标题不一致的美学映射拆分为多个图例,因此出现了重复图例。
解决方案
方案1:在labs()中统一所有相关美学属性的标题
直接在labs()里同时指定color、shape、linetype的标题为“Social Skills”,ggplot会自动将绑定同一变量的美学映射合并为单个图例:
intPlot <- ggplot(IntPoints2Plot, aes(sComplex, sPerform, color = sSkills, shape = sSkills, group = sSkills)) + geom_line(aes(linetype = sSkills)) + geom_point(size=5) + ylim(12,15) + theme(axis.text=element_text(size=11), axis.title=element_text(size=11), legend.title=element_text(size=11), legend.text=element_text(size=11)) + labs(x = "Social Complexity", y = "Social Performance", color = "Social Skills", shape = "Social Skills", linetype = "Social Skills") + theme_apa(x.font.size = 11, y.font.size = 11, legend.use.title = T) intPlot
方案2:使用guides()统一设置图例标题
通过guides()函数一次性为所有关联的美学映射设置相同标题,代码更简洁:
intPlot <- ggplot(IntPoints2Plot, aes(sComplex, sPerform, color = sSkills, shape = sSkills, group = sSkills)) + geom_line(aes(linetype = sSkills)) + geom_point(size=5) + ylim(12,15) + theme(axis.text=element_text(size=11), axis.title=element_text(size=11), legend.title=element_text(size=11), legend.text=element_text(size=11)) + labs(x = "Social Complexity", y = "Social Performance") + guides(color = guide_legend(title = "Social Skills"), shape = guide_legend(title = "Social Skills"), linetype = guide_legend(title = "Social Skills")) + theme_apa(x.font.size = 11, y.font.size = 11, legend.use.title = T) intPlot
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

