Try   HackMD

讓R以向量檔與自訂字型出圖

tags: 用R做

以往一直使用 Rstudio 的出圖功能,把繪製好的圖片設定長寬大小後,以 png 格式輸出,如果圖片的線條有弧線,就會在放大後看到邊緣不平滑,這是這類點陣圖(bitmap,或稱柵格圖 raster)的缺點。要解決這個問題,可以嘗試設定解析度,或者改用不同的格式試試:

png("plotname.png", width = 12, height = 8, units = 'in', res = 300)
tiff("plotname.tiff", width = 12, height = 8, units = 'in', res = 300)
#也可以用 cairo 出圖
library(Cairo)
Cairo(1200, 800, file = filename, type = "png", bg = "white", dpi = 300)

如果圖是用 ggplot 套件畫的,那也可以用套件裡的 ggsave() 函數,輸出一般會比 R base 再美一些,而且一樣的輸出設定,檔案也會更大一些(不知道為什麼):

#畫完圖之後緊接著
ggsave("plotname.png", width = 12, height = 8, dpi = 300)

如果強烈希望圖片不失真,可以使用向輛格式出圖,這樣無論如何伸縮,圖片的線條都可以永保銳利了。以常用的向量圖片格式 svg(scalable vector graphics)而言,可以在 Rstudio 當中出圖,但是遇到中文字,就會變成豆腐無法正常顯示,應該是算繪引擎(option 裡的 graphic divice 那項)沒辦法辨識與使用中文字型(或者所有的 unicodes)。
最後查到一個套件 showtext,可以讀入需要的字型檔,再配合 svg() 函數來出圖。只要輸入存於系統的字型檔(Windows 的路徑在 C:\Windows\Fonts)就可以調用字型,不過測試的時候發現還是要把字型檔複製到工作資料夾才能載入。以之前畫的溫度雨量圖中的年均溫變化為例,在繪圖函數上下加入有關圖片輸出的指令與 showtext 套件的函數,即可順利自訂字型,而且輸出銳利的向量檔。

#使用showtext加入字型
library(showtext)
font_add("GJ", "GenJyuuGothic-Regular.ttf")

#開始繪圖
svg("SiangshanTemp.svg", width = 12, height = 8)
showtext_begin()

tem <- ggline(total2, "year", "temp", size = 1, point.size = 1.5, color = "#7F1084") +
  labs(x = "\n 年度", y = "年均溫 (℃) \n", title = "香山氣象站 2008–2021年均溫變化") +
  scale_x_continuous(breaks = seq(2008, 2021, by = 1)) +
  scale_y_continuous(limits = c(22, 23.5), breaks = c(22.0, 22.25, 22.5, 22.75, 23.0, 23.25, 23.5)) +
  theme(plot.title = element_text(hjust = 0.5, face = "bold", size = 32),
        plot.margin = unit(c(1,2.5,1,1),'cm')) +
  font("xy.text", size = 18) +
  theme_hc()
ggpar(tem, font.family = "GJ", font.x = c(28, "azure4"), font.y = c(28, "azure4")) + 
  geom_hline(yintercept = 22.6583, lty = 5, color = "black")

showtext_end()
dev.off()

不過最後輸出的 svg 檔無法上傳到 hackmd,就只能在電腦上以網頁瀏覽器打開,然後截圖放上來了。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

svg 檔可以使用瀏覽器打開。

🐕‍🦺 2022.10.01