首页 > 解决方案 > 使用 cairo 使用非 ASCII 绘图标签的 ggsave

问题描述

我有一个带有绘图表达式的非 ASCII 轴标签。当我尝试使用 cairo 保存为 png 时,出现错误:

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

错误信息是:

Metric information not available for this family/device

另一方面,使用“windows”设备可以工作(警告除外):

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

警告(德语)是:

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

最后,如果标签不是绘图表达式,非 ASCII 轴标签本身不是问题:

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

最后一个命令不会引发错误。

但是,我更喜欢使用 cairo,因为它有时会画出更好的图片。有任何想法吗?

标签: rggplot2cairo

解决方案


这适用于具有 R 4.0.2 的 Windows 机器(也适用于 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")

reprex 包(v0.3.0)于 2020 年 7 月 7 日创建


推荐阅读