簡體   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