如何避免绘图下方的geom_text()被截断?
解决ggplot绘图下方geom_text文本被截断的问题
针对你遇到的柱状图下方多行文本被截断的问题,这里提供两种实用的解决思路:
方法1:扩展y轴显示范围
通过coord_cartesian()手动设置y轴的上下限,给下方的文本留出足够的显示空间。因为你的文本放置在y = -.4的位置,默认y轴从0开始,所以需要把y轴下限调整到比文本位置更低的数值:
library(dplyr) library(ggplot2) test <- tibble(group = c("\nA", "\nB"), score = c(100, 75), my_label = c("This group\n won the game\nYAY!", "This group\n lost the game\nBOO!")) ggplot(test, aes(x = group, y = score)) + geom_bar(stat = "identity") + geom_text(aes(label = my_label), size = 4.7, y = -.4, vjust = 1) + coord_cartesian(ylim = c(-15, 110)) # 按需调整下限数值,确保文本完全显示
方法2:调整绘图边距+扩展y轴空白
如果不想让y轴显示负数刻度,可以用scale_y_continuous()扩展y轴下方的空白区域,同时通过theme(plot.margin)增加绘图底部的边距,给文本留出空间:
ggplot(test, aes(x = group, y = score)) + geom_bar(stat = "identity") + geom_text(aes(label = my_label), size = 4.7, y = -.4, vjust = 1) + scale_y_continuous(expand = expansion(mult = c(0.15, 0.05))) + # 向下扩展y轴空白 theme(plot.margin = margin(b = 50, unit = "pt")) # 增加底部边距,单位可设为pt、mm等
你可以根据实际文本的行数和长度,灵活调整ylim的下限值、expansion的参数或者margin的数值,直到文本完全显示为止。
内容的提问来源于stack exchange,提问作者J.Sabree
相关产品推荐
相关产品推荐

