繁体   English   中英

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

[英]ggplot2 ggsave: keep embedded fonts in exported .png

许多人都遇到过自定义字体出现在 ggplot 中但在使用ggsave导出时消失的ggsave ,但我只找到了用于导出 pdf 的解决方案(例如ggplot 中的嵌入字体 pdf )。 我正在尝试导出为 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

2:

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

我如何绘制它:

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

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

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

没有 Karla 字体的 ggsave >:(

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

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

我发现如果我还在系统中安装了相关字体,则 png 输出可与 showfont 一起使用。 因此,例如,调用 showfont_auto() 将在 r 绘图显示中正确绘制字体,但保存为 png 不会呈现。 但是,如果我在我的计算机上安装了字体,它就会成功地将字体添加到 png 中(不必做任何困难的事情,比如将字体目录更新为 R 或类似的事情,只有 font_add_google("fontname") 如果它是例如来自谷歌字体的字体)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM