参考自《R Graphics Cookbook》
针对通过增加一列,然后再选择性地筛选要添加的变量,最后实现有选择性地对部分变量(点)添加标签的一种方法。
library(ggplot2)
library(gcookbook)
library(dplyr)
一、数据整理
#使用自带数据countries
#先筛选,然后复制Name列将其新增为一列,并转化为字符型变量,命名为plotname
cdat <- countries %>%
filter(Year == 2009, healthexp > 2000) %>%
mutate(plotname = as.character(Name))
#编辑想要展示的标签(此例中是国家名称)
countrylist <- c("Canada", "Ireland", "United Kingdom",
"United States","New Zealand", "Iceland",
"Japan", "Luxembourg", "Netherlands",
"Switzerland")
#进行逻辑判断,在countrylist中的plotname不改变其内容,否则为空值
cdat <- cdat %>%
mutate(plotname = ifelse(plotname %in%
countrylist, plotname, ""))
#查看是否不想添加标签的都变成了空值
cdat %>%
select(Name, plotname)
二、作图
ggplot(cdat, aes(x = healthexp, y = infmortality)) +
geom_point() +
#hjust = 0让标签右对齐,并且将标签映射到的x轴的位置往右多100的长度
geom_text(aes( x = healthexp + 100 , label = plotname),
size = 4, hjust = 0) +
#设置x轴上的显示范围
xlim(2000,10000)
![00470905e2011f597e56846afe710127.png](https://i-blog.csdnimg.cn/blog_migrate/124a156fa1b4bacedafe93a6f7eb31e6.png)
三、总结
实现在散点图中只添加部分标签的一种迂回的方法。