参考自《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, ""))