使用LM Roman 10字体时ggplot文本破折号与文字重叠的解决方法
title: "Untitled"
output: pdf_document
```{r setup, include=FALSE} knitr::opts_chunk$set( echo = FALSE, message=FALSE, warning=FALSE ) library(ggplot2) library(extrafont) df <- data.frame( x = c(1, 1, 2, 2, 1.5), y = c(1, 2, 1, 2, 1.5), text = c("bottom-left", "top-left", "bottom-right", "top-right", "label-with-dash") )
ggplot(df, aes(x, y)) + geom_text(aes(label = text))
ggplot(df, aes(x, y)) + geom_text(aes(label = text), family="LM Roman 10")
运行结果

解决方案
以下几种方法可在保留LM Roman 10字体的前提下解决破折号重叠问题:
微调字符间距:利用
geom_text()的kerning参数调整全局字符间距,数值可根据实际效果在0.05-0.2之间测试:ggplot(df, aes(x, y)) + geom_text(aes(label = text), family="LM Roman 10", kerning = 0.1)给破折号添加空格:将文本中的
-替换为-(前后加空格),适合对文本格式要求不严格的场景:df$text <- gsub("-", " - ", df$text) ggplot(df, aes(x, y)) + geom_text(aes(label = text), family="LM Roman 10")使用ggtext包渲染富文本:借助
ggtext的HTML格式化功能,单独给破折号添加边距,同时保留字体样式:
先安装并加载包:install.packages("ggtext") library(ggtext)然后修改文本并使用
geom_richtext渲染:df$text <- gsub("-", "<span style='padding:0 2px;'>-</span>", df$text) ggplot(df, aes(x, y)) + geom_richtext(aes(label = text), family="LM Roman 10", fill = NA, label.color = NA)fill=NA和label.color=NA用于移除默认的文本框背景与边框换用showtext包加载字体:
showtext对字体渲染的兼容性更强,能自动解决部分字符排版问题:
先安装并加载包,然后添加字体:install.packages("showtext") library(showtext) font_add("LM Roman 10", "lmroman10-regular.otf") # 替换为你的字体文件实际路径 showtext_auto() ggplot(df, aes(x, y)) + geom_text(aes(label = text), family="LM Roman 10")
内容的提问来源于stack exchange,提问作者Mads
相关产品推荐
相关产品推荐

