ggplot2搭配ggrepel添加图例时自定义标签颜色被修改问题咨询
问题原因
将十六进制颜色值列直接传入aes(colour)时,ggplot默认会将其识别为普通分类变量,自动分配默认调色板,不会直接取用色值本身,因此会出现预设色和实际渲染色不符的问题。
解决方案
提供两种实现方式,均可以保留自定义颜色同时生成对应排名的图例:
方式1:基于现有色值列搭配scale_colour_identity
直接告知ggplot取用颜色列的实际值作为渲染色,同时手动配置图例参数:
df2 %>% ggplot(aes(x = time, y = points_sum, group = name, label = name)) + geom_point() + geom_text_repel(direction = "y", size = 10, aes(colour = name_colour)) + scale_colour_identity( name = "排名", # 图例标题 breaks = c("#336600", "#339900", "#66ff33"), # 对应三个预设色值 labels = c("第1名", "第2名", "第3名"), # 色值对应的图例标签 guide = "legend" # 强制显示图例 ) + theme_minimal()
方式2:映射排名变量搭配scale_colour_manual(更推荐)
直接把排名作为映射变量,手动指定每个排名对应的色值,逻辑更清晰,后续调整更方便:
df2 %>% # 先把排名转为因子,设置顺序和标签 mutate(rank = factor(rank, levels = 1:3, labels = c("第1名", "第2名", "第3名"))) %>% ggplot(aes(x = time, y = points_sum, group = name, label = name)) + geom_point() + geom_text_repel(direction = "y", size = 10, aes(colour = rank)) + scale_colour_manual( name = "排名", values = c("第1名" = "#336600", "第2名" = "#339900", "第3名" = "#66ff33") ) + theme_minimal()
内容的提问来源于stack exchange,提问作者deschen
相关产品推荐
相关产品推荐

