rggplot2fontsgeom-text

Changing font to Arial (Liberation Sans) of ggplot2/geom_text


I've read this solution:

But it is Windows specific so it didn't work for me.

Is there another solution? I've loaded my font like this:

install.packages("showtext")
library(showtext)
font_add("Arial", "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", bold = "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", italic = "/usr/share/fonts/truetype/liberation/LiberationSans-Italic.ttf", bolditalic = "/usr/share/fonts/truetype/liberation/LiberationSans-BoldItalic.ttf")

Which I then use with:

theme(text=element_text(family = "Arial"))

However geom_text doesn't inherit font from element_text, so how can I change it? Simply adding family = "Arial" to geom_text parameters gives this error:

Warning message in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x x$y:
"font family 'Arial'" not found in PostScript font database

Even if I use solution here it keeps giving the same error. I just did what the solution suggested:

theme_set(theme_minimal(base_family = "Arial"))
update_geom_defaults("text", list(colour = "grey20", family = theme_get()$text$family))

And it raises exactly same error. Very likely it is now obsolete...

Here is a minimal sample for reproducibility: (First I install the font with: apt install ttf-mscorefonts-installer)

library(ggplot2)

# Generate random data
set.seed(123)  # For reproducibility
data <- data.frame(
  x = rnorm(20, mean = 50, sd = 10),  # Random x values
  y = rnorm(20, mean = 50, sd = 10),  # Random y values
  label = paste("P", 1:20, sep = "")  # Point labels
)

# Create scatter plot with labels
ggplot(data, aes(x = x, y = y)) +
  geom_point(color = "blue", size = 3) +  # Scatter plot points
  geom_text(aes(label = label), vjust = -1, hjust = 0.5, size = 5, color = "red", family='Arial') +  # Labels
  theme_minimal() +
  theme(text=element_text(family = "Arial")) + 
  labs(title = "Random Scatter Plot with Labels",
       x = "X-axis",
       y = "Y-axis")

Solution

  • Found out that the solution was actually quite simple. Just adding: showtext_auto() before plotting.

    But one should also add showtext_opts(dpi = 300) since for some reason it messes up font sizes when saving plot with ggsave.