ggplot中geom_text未显示完整数据的问题咨询
问题:geom_text未显示全部国家文本的原因及解决方法
我的数据集里每个年份都包含5个国家,但使用上述代码绘制时,除2030年外,其余年份均未显示全部5个国家的文本,请问这是什么原因?
数据集与代码
dat <- structure(list(Country = c("Rwanda", "Uganda", "Honduras", "Slovenia", "Bosnia and Herzegovina", "Rwanda", "Slovenia", "El Salvador", "Bosnia and Herzegovina", "Slovakia", "Lithuania", "Trinidad and Tobago", "Rwanda", "Honduras", "Uganda", "Lithuania", "Poland", "Slovakia", "Finland", "Serbia"), Year = c("2020", "2020", "2020", "2020", "2020", "2030", "2030", "2030", "2030", "2030", "2040", "2040", "2040", "2040", "2040", "2050", "2050", "2050", "2050", "2050" ), x = c(3.52229269054852, 3.48719818221878, 3.27479730257771, 3.23749207619133, 3.21860068070842, 4.03311621112984, 3.84576854280025, 3.59225623413964, 3.53162905338438, 3.49789347217355, 3.66601597889191, 3.65257647482563, 3.65087176257351, 3.52944633458076, 3.48476020371068, 4.97433423368669, 4.91067633570393, 4.72467884942941, 4.72059996530178, 4.66345169203987)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame")) library(ggplot2) ggplot(dat, aes(x = Year, y = x, label = factor(Country))) + geom_text(check_overlap = TRUE)
原因分析
问题出在geom_text()的check_overlap = TRUE参数上:这个参数会自动检测并隐藏重叠的文本标签。
看数据里的x值:
- 2020年的5个国家x值集中在3.2-3.5区间,数值差距小,文本标签重叠,因此部分被隐藏;
- 2040年的Lithuania(3.666)、Trinidad and Tobago(3.652)、Rwanda(3.650)三个x值几乎重合,标签完全重叠,所以只显示了一个;
- 2050年的前四个国家x值也非常接近,同样出现重叠被隐藏的情况;
- 只有2030年的x值间隔相对较大(3.49-4.03),标签没有重叠,所以全部显示。
解决方法
方法1:关闭重叠检测
直接去掉check_overlap = TRUE,所有标签都会显示,但可能出现严重重叠:
ggplot(dat, aes(x = Year, y = x, label = factor(Country))) + geom_text()
方法2:添加随机偏移
用position_jitter()给标签加少量随机位移,避免重叠:
ggplot(dat, aes(x = Year, y = x, label = factor(Country))) + geom_text(position = position_jitter(width = 0.1, height = 0.05))
可以调整width和height参数控制偏移幅度。
方法3:使用ggrepel包自动调整标签
ggrepel包的geom_text_repel()会智能调整标签位置,自动避开重叠:
library(ggrepel) ggplot(dat, aes(x = Year, y = x, label = factor(Country))) + geom_text_repel()
内容的提问来源于stack exchange,提问作者89_Simple
相关产品推荐
相关产品推荐

