ggplot2 ggsave:将嵌入的字体保留在导出的 .png 中

spo*_*ops 5 r ggplot2

许多人都遇到过自定义字体出现在 ggplot 中但在使用 导出时消失的问题ggsave,但我只找到了用于导出 pdf 的解决方案(例如 pdf 中的ggplot 嵌入字体)。我正在尝试导出为 png。这以前对我来说效果很好,所以不确定发生了什么。

刚刚更新了所有内容,但没有解决问题 - R 版本为 3.5.0;RStudio 为 1.1.453;在 macOS Sierra 上。

这两项工作都可以将字体添加到绘图中:

1:

if (!require(showtext)) {
  install.packages("showtext", repos = "http://cran.utstat.utoronto.ca/")
  require(showtext)
}
font_add_google("Karla", "karla") # Add nice google font
showtext_auto() # Tell R to use showtext to render google font
Run Code Online (Sandbox Code Playgroud)

2:

if (!require(extrafont)) {
  install.packages("extrafont", repos = "http://cran.utstat.utoronto.ca/")
  require(extrafont)
}
font_import(pattern = "Karla")
Run Code Online (Sandbox Code Playgroud)

我如何绘制它:

theme_map <- function(...) {
  theme_minimal() +
    theme(
      text = element_text(family = "Karla", color = "#22211d"),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_blank(),
      plot.background = element_rect(fill = "#f5f5f2", color = NA), 
      panel.background = element_rect(fill = "#f5f5f2", color = NA), 
      legend.background = element_rect(fill = "#f5f5f2", color = NA),
      panel.border = element_blank(), # infuriatingly doesn't work but that's unrelated
      aspect.ratio = 9 / 16, # 16:9 aspect ratio
      ...
    )
}

data(iris)

p <- ggplot() + geom_point(data=iris, aes(x=iris$Sepal.Length, y=iris$Sepal.Width)) + labs(title="Font Pls") + theme_map()

plot(p)

ggsave("iris.png", p, device="png")
ggsave("iris.png", p, device="png", type="cairo") # does not produce an error but also doesn't produce a .png file
ggsave("iris.png", p, device="cairo-png") # also does not produce an error but also doesn't produce a .png file
Run Code Online (Sandbox Code Playgroud)

我在 RStudio 中看到的(并想保存): 与卡拉的 RStudio 情节! :)

使用 ggsave 保存的内容:ggsave即使使用type = "cairo-png"或 等其他地方提供的解决方案, 这也是使用 吐出的内容type = "cairo"。(添加其中任何一个只会产生错误,根本不会保存绘图。)不确定它是否相关(尽管可能是),但 ggsave 似乎也忽略了标题、轴、等等。

没有 Karla 字体的 ggsave >:(

如果它在那里,我很高兴使用非 ggsave 解决方案。我有数百张图像需要以这种格式导出,因此“将其导出为 pdf 然后另存为 png”不是一个选项。

spo*_*ops 0

绝对不是完整的答案,但我已经能够通过重新启动 R,然后仅加载绘图、绘图和保存所需的 ggplot2 和比例库来解决此问题。所以我正在使用的其他一些软件包会干扰 ggsave。