ggplot中shape形状图例不生效 显示形状与设置不符问题求助
问题原因
你将shape参数写在了aes()之外,属于对当前图层所有点的固定赋值,没有将形状和分类变量建立美学映射关系,所以你写的scale_shape_manual没有可映射的变量,自然不会生效。同时两个geom_point仅在aes()中声明了colour映射,ggplot合并颜色、形状两个图例时就会出现形状匹配错误的问题。
解决方法
修改两个geom_point层的代码,将shape也放入aes()中,和colour使用相同的分类变量映射,修改后的完整代码如下:
# 注意颜色值如果是内置色名需要加引号,如果你之前已经定义了maroon、grey变量可以去掉引号 cols <- c("Bonus" = "maroon", "Limit" = "grey") a <- ggplot(periodtreatments, aes(x=names, width=.2)) + # 把shape也放进aes里做映射 geom_point(aes(y=bonus_coefs, colour="Bonus", shape="Bonus"), stat="identity", position = position_nudge(x = -.1)) + geom_point(aes(y=limit_coefs, colour="Limit", shape="Limit"), stat="identity", position = position_nudge(x = .1)) + geom_errorbar(aes(ymin=bonus_upper, ymax=bonus_lower, width=0.09), size =0.8, stat="identity", colour="maroon", position = position_nudge(x = -.1)) + geom_errorbar(aes(ymin=limit_lower, ymax=limit_upper, width=0.09), size =0.8, stat="identity", colour="grey", position=position_nudge(x = .1)) + scale_y_continuous(name="Treatment effect (minutes/day)") + theme_classic() + labs(x = "") + theme(legend.text.align = 0, legend.key.height = unit(1, "cm"), legend.position="bottom") + theme(legend.margin=margin(0,0,0,0), legend.box.margin=margin(-10,-10,-10,-10)) + theme(axis.text.x = element_text(colour="black")) + coord_cartesian(ylim = c(-70, 5)) + theme(legend.text=element_text(size=11)) + theme( panel.grid.major.x = element_blank() , panel.grid.major.y = element_line( size=.05, color="grey" ) )+ scale_colour_manual(name = "", values=cols, labels = c("Bonus", "Limit"))+ scale_shape_manual(name = "", labels = c("Bonus", "Limit"), values = c(16, 15))
修改后颜色和形状两个美学维度都和Bonus/Limit分类变量绑定,两个比例尺的名称完全一致,ggplot会自动将两个图例合并为一个,形状和颜色就能正确匹配。
内容的提问来源于stack exchange,提问作者Lola1993
相关产品推荐
相关产品推荐

