如何为ggplot2中geom_point图层手动添加图例项
解决ggplot中手动添加固定形状/颜色的图例项问题
ggplot的图例是基于**美学映射(aes)**生成的,你之前把红色叉形的shape和col放在aes()外面作为固定参数,所以ggplot不会为它们创建图例。要添加这个图例项,得把这两个属性移入aes(),再用手动刻度函数指定对应的固定值,具体修改如下:
修改后的完整代码
ggplot() + # 把shape和col移入aes,用字符串作为映射标识 geom_point(data = data.rf[1077:2152, ], aes(x = mean_Tmean_Summer, y = mean_Precip_Summer, shape = "无火区", col = "无火区"), alpha = 0.5) + # 保持原有带size映射的图层 geom_point(data = data.rf[1:1076, ], aes(x = mean_Tmean_Summer, y = mean_Precip_Summer, size = fires$Fire_Ar), alpha = 0.5) + # 手动指定shape映射的对应值 scale_shape_manual(name = "组别", values = c("无火区" = 4)) + # 手动指定color映射的对应值 scale_color_manual(name = "组别", values = c("无火区" = "darkred")) + # 原有火区面积的size刻度设置 scale_size(name = bquote("Fire Area "(m^2)), breaks = c(500, 1000, 1500, 2000, 2500)) + theme_bw() + xlab("Mean Summer Temperature (°C)") + ylab("Mean Summer Precipitation (mm)") + # 调整图例顺序,让组别图例排在前面 guides(shape = guide_legend(order = 1), size = guide_legend(order = 2))
关键修改说明
- 将固定属性移入aes:给红色叉形图层的
shape和col指定一个字符串标识(比如"无火区"),让ggplot识别这是需要生成图例的映射项。 - 手动指定映射值:用
scale_shape_manual和scale_color_manual把刚才的字符串标识对应到你想要的形状(4)和颜色(darkred),同时统一图例标题。 - 移除无用的scale_color_viridis:你第二个图层没有映射color属性,这个刻度函数根本不起作用,直接删掉就行。
- 调整图例顺序:用
guides()可以控制不同图例的显示顺序,让组别图例优先展示。
如果需要给第二个图层也添加图例项,只需要在它的aes()里加入col = "有火区",然后在scale_color_manual里补充对应颜色值即可。
内容的提问来源于stack exchange,提问作者apple
相关产品推荐
相关产品推荐

