如何避免ggplot2中geom_text标签被截断且无需手动设置vjust
方案1:调整y轴留白(无需额外安装包)
标签截断的核心原因是绘图区域的y轴边界没有预留足够空间容纳超出点位置的文本,只需在原有代码基础上增加scale_y_continuous()的expand参数,按比例给y轴上下方统一增加留白即可,自动适配所有分面的free_y尺度:
library(tidyverse) data <- structure(list(Date = structure(c(18779, 18809, 18840, 18871, 18901, 18932, 18779, 18809, 18840, 18871, 18901, 18932, 18779, 18809, 18840, 18871, 18901, 18932), class = "Date"), Key = c("Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3"), Value = c(2.8, 3, 2, 2.7, 2.7, 2.8, 1, 2, -1.2, 0.3, 0.6, 0.8, 4, 3.7, 4.4, 4.4, 4.2, 4.2)), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame")) ggplot(data, aes(Date, Value, col = Key)) + geom_line(size = 2) + facet_wrap(~Key, scales = 'free_y', nrow = 3) + guides(col='none', linetype='none') + # 新增y轴留白配置,上下各预留15%的空间容纳标签 scale_y_continuous(expand = expansion(mult = c(0.15, 0.15))) + geom_text(aes(label = paste0(sprintf('%0.1f', round(Value, digits = 2)), '%')), size = 5, vjust = -1)
可根据文本大小调整mult的数值,数值越大预留留白越多。
方案2:使用ggrepel自动调整标签位置
如果同时需要避免标签重叠、自动规避绘图边界,可以使用ggrepel包的geom_text_repel替代原生geom_text,无需手动配置逐个位置参数,会自动适配所有数值变动调整标签位置:
首先安装依赖包:install.packages("ggrepel"),运行代码如下:
library(tidyverse) library(ggrepel) data <- structure(list(Date = structure(c(18779, 18809, 18840, 18871, 18901, 18932, 18779, 18809, 18840, 18871, 18901, 18932, 18779, 18809, 18840, 18871, 18901, 18932), class = "Date"), Key = c("Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3"), Value = c(2.8, 3, 2, 2.7, 2.7, 2.8, 1, 2, -1.2, 0.3, 0.6, 0.8, 4, 3.7, 4.4, 4.4, 4.2, 4.2)), row.names = c(NA, -18L), class = c("tbl_df", "tbl", "data.frame")) ggplot(data, aes(Date, Value, col = Key)) + geom_line(size = 2) + facet_wrap(~Key, scales = 'free_y', nrow = 3) + guides(col='none', linetype='none') + geom_text_repel(aes(label = paste0(sprintf('%0.1f', round(Value, digits = 2)), '%')), size = 5, # 可调整参数控制标签和点的距离、重叠规则 nudge_y = 0.1, max.overlaps = Inf)
内容的提问来源于stack exchange,提问作者sa90210
相关产品推荐
相关产品推荐

