簡體   English   中英

"在 R 中使用 Cairo 更改繪圖字體"

[英]Changing Plot Font with Cairo in R

我發現 R 的默認圖的別名很差。 作為一種解決方案,我將 Cairo 設置為圖形設備,現在繪圖看起來好多了。

不幸的是,使用 Cairo 產生了另一個問題,即由於某種原因,我無法應用在繪圖窗口中顯示圖表時使用的字體(在上面的左側圖中,使用了 Cambria,但右圖未能應用此字體)。

這是我的代碼:

library(readxl)
library(scales)
library(ggplot2)
library(dplyr)
library('Cairo')

windowsFonts(Cam = windowsFont("Cambria"))

dataset <- read_excel('CW Data.xlsx')
colnames(dataset)[4] <- "Broadband Subs (%)"

options(scipen = 1000)

# Scatter plot FDI~GDP with regression line
CairoWin()
ggplot(dataset, aes(x=`2019 GDP ($bn)`, y=`2019 FDI ($m)`)) + 
  geom_point(size=3, shape=1) +
  geom_smooth(method='lm',formula=y~x, se=FALSE, color='black') +
  scale_x_continuous(label = comma) + scale_y_continuous(label=comma) +
  theme(panel.background = element_rect(fill="peachpuff"), 
        plot.background = element_rect(fill="peachpuff")) +
  theme(panel.grid.major = element_line(colour = "gray72"), 
        panel.grid.minor = element_line(colour = "gray72")) + 
  theme(text = element_text(family = "Cam")) 

ggsave("FDI~GDP.png", device="png", type = "cairo") 

這是我正在使用的 Excel 數據的 OneDrive 鏈接

https://1drv.ms/x/s!AvGKDeEV3LOs4gNr714Ie0KbOjhO?e=bkdPvk

請不要將此視為問題的答案,而應將其視為賞金的激勵示例。

我發現 PDF 設備使用自定義字體給出​​了絕對糟糕的結果。 關於賞金,這里有一個更小的代表。

library(ggplot2)

p <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point() +
  theme(text = element_text(family = "mono"))

ggsave("font_test.pdf", p, device = cairo_pdf)
#> Saving 7 x 5 in image

reprex 包於 2022-02-04 創建 (v2.0.1)

PDF輸出的截圖:

在此處輸入圖像描述

我不需要向敏銳的印刷師解釋顯示的單聲道字體不是“Courier New”或系統默認的等寬字體。 此外,左軸標題被破壞,圖例標題不正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM