R语言 字体使破折号与文本冲突

jgwigjjp  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(143)

当我在ggplot中将字体更改为LM Roman 10时,它会使破折号与字母发生冲突。如何在仍使用此字体的情况下解决此问题?

---
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") 

下面是上面代码的结果:

![](https://i.stack.imgur.com/Jbad1.png)
5cg8jx4n

5cg8jx4n1#

通过创建一个函数将破折号替换为unicode破折号来修复它:

fixl <- function(x){
  return(gsub("-", "\u00ad", x, fixed=TRUE))
}

然后可以将其应用于图,如:

p <- ggplot(df, aes(x, y)) +
  geom_text(aes(label = fixl(text)), family="LM Roman 10") + 
  scale_y_continuous(limits = c(-5,5), labels=fixl) + 
  theme(text = element_text(size=10, family="LM Roman 10"))
p

相关问题