如何为ggplot2散点图图例值标签着色以匹配散点颜色?
ggplot2:让图例标签颜色与散点颜色匹配
问题
如何将散点图中图例的灰色值标签,设置成对应散点的颜色?
初始代码
library(ggplot2) ggplot(diamonds, aes(x=carat, y=price, col=cut)) + geom_point()
解决办法
可以通过两种方式实现标签颜色与散点颜色的匹配:
方式一:在颜色刻度中配置图例
借助scale_color_discrete()的guide参数,直接给图例标签指定对应颜色:
library(ggplot2) ggplot(diamonds, aes(x=carat, y=price, col=cut)) + geom_point() + scale_color_discrete( guide = guide_legend( label.theme = element_text( color = scales::hue_pal()(length(unique(diamonds$cut))) ) ) )
方式二:通过主题设置动态绑定颜色
先提取当前颜色映射的颜色值,再在theme()中设置图例文本颜色:
library(ggplot2) library(scales) # 获取cut类别数量,生成对应颜色向量 label_colors <- hue_pal()(length(unique(diamonds$cut))) ggplot(diamonds, aes(x=carat, y=price, col=cut)) + geom_point() + theme(legend.text = element_text(color = label_colors))
两种方法都能让每个图例标签的颜色,和对应类别的散点颜色完全一致,按需选择即可。
内容的提问来源于stack exchange,提问作者user115916
相关产品推荐
相关产品推荐

