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

时间:2018-05-28 01:27:01

标签: r ggplot2

很多人都遇到过ggplot中出现自定义字体的问题,但是在使用ggsave导出时会消失,但我只找到了导出pdf的解决方案(例如ggplot embedded fonts in 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 plot with Karla! :)

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

ggsave without Karla font >:(

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

1 个答案:

答案 0 :(得分:0)

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

相关问题