Search code examples
rggplot2cairo

ggsave with non-ASCII plotmath labels using cairo


I have a non-ASCII axis label with a plotmath expression. When I try to save as png using cairo, I get an error:

library(ggplot2)
ggsave("test.png",
       qplot(mtcars$hp, mtcars$cyl) +
         ylab(expression(`cÜl`~italic(r)(italic(M)))) +
         xlab(expression(hp~italic(hp))),
       device = grDevices::png,
       type = "cairo")

The error message is:

Metric information not available for this family/device

On the other hand, using the "windows" device works (except for a warning):

ggsave("test.png",
       qplot(mtcars$hp, mtcars$cyl) +
         ylab(expression(`cÜl`~italic(r)(italic(M)))) +
         xlab(expression(hp~italic(hp))),
       device = grDevices::png,
       type = "windows")

The warning (in German) is:

In dev(filename = filename, width = dim[1], height = dim[2], ...) :
  'width=7, height=7' sind unwahrscheinliche Pixelzahlen

Finally, non-ASCII axis labels are not a problem per se, if the label is not a plotmath expression:

ggsave("test.png",
       qplot(mtcars$hp, mtcars$cyl) +
         ylab("cÜl") +
         xlab(expression(hp~italic(hp))),
       device = grDevices::png,
       type = "cairo")

The last command raises no error.

However, I would prefer to use cairo, since it draws nicer pictures sometimes. Any ideas?


Solution

  • This worked on a Windows machine with R 4.0.2 (and also on linux):

    library(ggplot2)
    library(ggtext)
    
    ggsave("test.png", width = 6, height = 6,
           qplot(mtcars$hp, mtcars$cyl) +
               labs(x = "hp *hp*",
                    y = "c\u00DCl *r*(*M*)") +
               theme(
                   axis.title.x = element_markdown(),
                   axis.title.y = element_markdown()
               ),
           type = "cairo-png")
    

    Created on 2020-07-07 by the reprex package (v0.3.0)