0

When I change the font to LM Roman 10 in a ggplot, it makes the dashes collide with the letters. How do I fix this, while still using this font?

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


```{r test1, echo=FALSE, out.width = '80%'}
ggplot(df, aes(x, y)) +
geom_text(aes(label = text))
```

```{r test2, echo=FALSE, out.width = '80%'}
ggplot(df, aes(x, y)) +
geom_text(aes(label = text), family="LM Roman 10") 
```

Here is the result of the code above:

result of code

Mads
  • 85
  • 1
  • 7

1 Answers1

0

Fixed it by making a function that replaces the dashes with unicode dashes:

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

that can then by applied to the plot like:

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

result

Mads
  • 85
  • 1
  • 7