'Use monospaced font for axis labels in ggplot2 with png output

I work with genomic data where I want to plot the frequency of trinucleotides. I want to generate a png plot with ggplot2 and I work on a Linux Centos computer. As you see in the figure, the x.axis labels are not perfectly aligned as the letters don't have the same size. I want to use a monospaced font so I tried the "family" argument to modify the theme but this has no effects. I have seen and tested many answers using the "extrafont" package with no results as it doesn't seem to work for png outputs. Is there a simple way of using a monospaced font (e.g. Courier) in ggplot2 with or without using additional package ?

enter image description here

This is an example of my code so far based on a minimal dataset.

testData <- data.frame(freq = rnorm(10),
                       context = c("ACA","ACC","ACG","ACT","CCA",
                                   "CCC","CCG","CCT","GCA","GCC"))
a <- ggplot(testData, aes(x=context, y=freq)) + 
  geom_bar(stat="identity", width = 0.4, fill = "royalblue") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5,
                                   size = 10, family = "mono"),
        axis.title.x=element_blank())
ggsave("test.png",
       plot=a,
       width=2, height=2,
       device = "png",
       dpi = 300,
       type = "cairo")


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source