首页 > 解决方案 > 如何将 geom_label_repel 映射到 ggplot2 中的颜色

问题描述

我制作了一个数据集的箱线图。引入了一个新人,我想用 geom_label_repel 在现有数据集上绘制这个人。但是,不考虑颜色(可能是因为它的数据集不同)。

有没有办法用旧数据集中的颜色绘制丽莎?

library(ggplot2)
library(ggrepel)

xDF <- data.frame(age=c(20,22,25,27,44, 34, 28, 32) ,
                 sex = c("F", "F", "M", "F", "M", "M", "F", "M"),
                 Home_city =c("NY", "LA","NY", "LA", "LA", "LA","NY","NY") )

new_person <- data.frame(age=40, sex="F", Home_city="NY", name= "Lisa")

 ggplot(data=xDF, aes(x=Home_city, y=age, color=sex))+
     geom_boxplot()+
     geom_label_repel(data=new_person, aes(x=Home_city, y=age, color=sex, label=name),
               box.padding   = 0.35, 
               point.padding = 0.5,
               segment.color = 'grey50')

标签: rggplot2

解决方案


有两个问题,首先您需要“躲避” boxplot 之类的标签,这是使用 完成的position=position_dodge2(width=..),并调整此参数内的宽度,因为使用 geom_repel() 不清楚您想将其放置在哪里。例如下面的代码适用于 2 个标签(M+F):

library(ggplot2)
library(ggrepel)

new_2p <- data.frame(age=c(40,40), sex=c("F","M"), 
Home_city="NY", name= "Lisa")

ggplot(data=xDF, aes(x=Home_city, y=age, color=sex))+
geom_boxplot()+
geom_label_repel(data=new_2p, aes(label=name),show.legend=FALSE,
               position = position_dodge2(width = 0.5),
               box.padding   = 0.35, 
               point.padding = 0.5,
               segment.color = 'grey50')

在此处输入图像描述

但是你有一个问题,因为只有 1 个标签,所以它不知道如何“躲避”,一个快速的解决方法是将离散转换为数字并手动定位它:

new_person$Home_city <- factor(new_person$Home_city,levels=levels(xDF$Home_city))

ggplot(data=xDF, aes(x=Home_city, y=age,color=sex))+
geom_boxplot()+
geom_label_repel(data=new_person, 
                 aes(x=as.numeric(Home_city)-0.15,label=name),
                 box.padding   = 0.35, 
                 point.padding = 0.5,
                 segment.color = 'grey50')

在此处输入图像描述


推荐阅读