ggplot2:点按变量着色隐藏图例,仅保留geom_smooth国家图例
解决ggplot2中散点图图例无法隐藏的问题
当两个图层同时使用color美学映射时,ggplot2会自动合并所有关联的图例项,仅给geom_point设置show.legend = FALSE无法彻底隐藏director对应的图例,因为全局图例包含了所有color映射的类别。以下是几种可行的解决方案:
方案一:手动覆盖图例样式
通过guides()函数指定图例仅显示拟合线样式,隐藏散点相关的图例项:
ggplot(filtered_movies, aes(x = earnings, y = imdb_score)) + geom_smooth(aes(color = country), method = "lm") + geom_point(aes(color = director), alpha = 0.7, size = 3) + guides(color = guide_legend(override.aes = list(shape = NA, linetype = 1))) + theme_classic()
这里通过override.aes设置图例只显示拟合线(linetype = 1),将散点形状设为NA隐藏,从而剔除director类别在图例中的展示。
方案二:限定图例仅包含目标类别
使用scale_color_discrete()的breaks参数,指定图例仅显示country的唯一值,配合show.legend = FALSE彻底隐藏散点图例:
ggplot(filtered_movies, aes(x = earnings, y = imdb_score)) + geom_smooth(aes(color = country), method = "lm") + geom_point(aes(color = director), alpha = 0.7, size = 3, show.legend = FALSE) + scale_color_discrete(breaks = unique(filtered_movies$country)) + theme_classic()
breaks参数限定了图例仅展示country的类别,director的颜色映射不会被纳入图例范围。
方案三:分离美学映射(可选)
将散点的着色改为fill美学(需使用支持填充的点形状,如shape = 21-25),让散点和拟合线的图例完全独立:
ggplot(filtered_movies, aes(x = earnings, y = imdb_score)) + geom_smooth(aes(color = country), method = "lm") + geom_point(aes(fill = director), shape = 21, alpha = 0.7, size = 3, show.legend = FALSE) + theme_classic()
此方法下,散点使用fill着色,拟合线使用color,两者图例无冲突,设置show.legend = FALSE即可直接隐藏散点的填充图例。
内容的提问来源于stack exchange,提问作者Winston Castorp
相关产品推荐
相关产品推荐

