如何解决ggplot2选择性标注特定散点时的报错问题?
解决ggplot2散点图特定点标注的长度不匹配报错问题
数据样例
"Country","Continent","GDP","HCI" Afghanistan,Asia,1991,0.40 Albania,Europe,19566,0.63 Algeria,Africa,13682,0.53 Angola,Africa,7077,0.36 Antigua and Barbuda,Americas,25449,0.60 Argentina,Americas,26506,0.60 ...
报错代码
ctry_inf <- read.csv("Paises_PIB_ICH.csv") ctry_inf_selec <- ctry_inf[ctry_inf$Continent == "Asia" | ctry_inf$Continent == "Africa", ] ggplot(ctry_inf_selec, aes(x=GDP, y=HCI)) + geom_point() + scale_x_continuous(trans='log10') + geom_text(aes(label = ifelse(ctry_inf$Country == "Namibia" | ctry_inf$Country == "United Arab Emirates", as.character(Country), "")))
报错信息
> ggplot(ctry_inf_selec, aes(x=GDP, y=HCI)) + geom_point() + + scale_x_continuous(trans='log10') + + geom_text(aes(label = ifelse(ctry_inf$Continent == "Asia", as.character(Country), ""))) Error in `geom_text()`: ! Problem while computing aesthetics. ℹ Error occurred in the 2nd layer. Caused by error in `check_aesthetics()`: ! Aesthetics must be either length 1 or the same as the data (91) ✖ Fix the following mappings: `label` Run `rlang::last_trace()` to see where the error occurred.
问题原因
报错核心是**geom_text的label美学映射长度与当前图层数据集长度不匹配**:你在ifelse里引用了原始数据集ctry_inf$Country,而当前图层用的是筛选后的ctry_inf_selec(共91行),原始数据集行数多于91,导致生成的label向量长度和图层数据不一致,触发ggplot的美学检查报错。
解决方案(两种方法,均仅用ggplot2)
方法1:修正ifelse的数据集引用
直接使用当前图层的数据集列名(ggplot会自动继承ctry_inf_selec),不需要加ctry_inf$前缀:
ctry_inf <- read.csv("Paises_PIB_ICH.csv") ctry_inf_selec <- ctry_inf[ctry_inf$Continent == "Asia" | ctry_inf$Continent == "Africa", ] ggplot(ctry_inf_selec, aes(x=GDP, y=HCI)) + geom_point() + scale_x_continuous(trans='log10') + geom_text(aes(label = ifelse(Country == "Namibia" | Country == "United Arab Emirates", as.character(Country), "")))
方法2:单独给geom_text指定目标数据集(更高效)
只给需要标注的两个国家生成文本,避免生成大量空字符串:
ctry_inf <- read.csv("Paises_PIB_ICH.csv") ctry_inf_selec <- ctry_inf[ctry_inf$Continent == "Asia" | ctry_inf$Continent == "Africa", ] # 筛选出需要标注的国家 label_data <- ctry_inf_selec[ctry_inf_selec$Country %in% c("Namibia", "United Arab Emirates"), ] ggplot(ctry_inf_selec, aes(x=GDP, y=HCI)) + geom_point() + scale_x_continuous(trans='log10') + geom_text(data = label_data, aes(label = Country))
两种方法都能解决长度不匹配的问题,方法2更轻量化,推荐使用。
内容的提问来源于stack exchange,提问作者Luís Frederico Santos
相关产品推荐
相关产品推荐

