R语言使用gplots包textplot()绘制文本被截断如何调整适配?
gplots包textplot文本截断的解决方法
核心原因
textplot() 本身不会对传入的长文本自动做换行适配,当传入的单行文本长度超过绘图区域可用宽度、边距设置不合理、对齐方式选择不当时,超出边界的文本就会被直接截断。
可直接复现的调整方案
最稳妥的实现方式是先对长文本做自动折行,再配合参数优化适配绘图区,参考代码如下:
library(gplots) raw_text <- "R is a programming language for statistical computing and graphics supported by the R Core Team and the R Foundation for Statistical Computing. Created by statisticians Ross Ihaka and Robert Gentleman, R is used among data miners, bioinformaticians and statisticians for data analysis and developing statistical software.[6] Users have created packages to augment the functions of the R language. According to user surveys and studies of scholarly literature databases, R is one of the most commonly used programming languages used in data mining.[7] As of March 2022, R ranks 11th in the TIOBE index, a measure of programming language popularity, in which the language peaked in 8th place in August 2020" # 按指定每行字符数自动折行,width值可根据画布大小、字号调整 wrapped_text <- paste(strwrap(raw_text, width = 75), collapse = "\n") # 绘图前可先设置足够大的画布,根据自己的设备调整尺寸 # windows(width=10, height=7) # Windows系统用 # quartz(width=10, height=7) # Mac系统用 # X11(width=10, height=7) # Linux系统用 textplot(wrapped_text, halign = "left", # 长文本优先左对齐,避免右对齐贴边截断 valign = "top", # 从顶部开始排版,避免行数过多时顶部内容被裁切 cex = 0.6, # 字号可根据显示效果微调 fixed.width = FALSE, # 关闭固定等宽排版,按字符实际宽度排布更紧凑 cspace = 1, lspace = 1.2, # 适当调大行间距避免拥挤 mar = c(2, 2, 2, 2) + 0.1, # 四周留均匀边距,不要把侧、下边距设为0 tab.width = 8)
参数调整说明
- 预折行是最核心的步骤:基础绘图体系下没有自动长文本换行逻辑,必须用
strwrap()提前把长文本拆分为适合画布宽度的短行,若运行后仍有横向截断,可把strwrap()的width参数调小,或降低cex字号 - 不要把左右、下侧边距设为0:边距为0时文本直接贴在绘图边界,哪怕超出一点点都会被截断,四周留1-2单位的边距可以给文本留足够的缓冲空间
- 长文本不建议用右对齐、底部对齐:右对齐时文本右边缘紧贴绘图区右侧,底部对齐时文本从下往上排布,内容稍多就会出现边缘裁切,左对齐+顶部对齐的适配性最好
- 如果需要导出图片,直接在
png()/pdf()等绘图设备函数里设置足够大的宽高,再运行textplot代码即可,不会出现截断。
内容的提问来源于stack exchange,提问作者user18937485
相关产品推荐
相关产品推荐

