r - 如何将 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')
解决方案
有两个问题,首先您需要“躲避” 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')
推荐阅读
- typescript - 是否有为您的模块创建桶的自动替代方法?
- r - R Shiny:markdown表格单元格内的代码输出
- python - 如何在python中找到所选多边形半径内的多边形?
- python - 使用 .save() 方法将数据保存到 django 中的数据库时出错
- ios - 如何将应用程序用户与用于 IAP 的苹果 ID 相关联?
- python - 并非所有从 Beautifulsoup find_all 方法返回的 HTML 元素
- firebase - undefined 不是对象(评估'_this2.props')onPress
- node.js - MongoDB 数据比预期更早过期(node js、mongoose)
- python - 对文件夹 python 中的 40k 图像进行排序
- pyspark - 即使不满足插入条件,Delta Lake 插入也会重写数据