首页 > 解决方案 > 在 R 中使用 Cairo 更改绘图字体

问题描述

我发现 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

标签: rggplot2fontscairo

解决方案


我建议你看看包raggsystemfonts. 它们使使用字体变得非常容易,并且结果比基本选项的输出要好。

首先,我建议您使用View(systemfonts::system_fonts()). 您可以选择此处存在的每种字体并将其用于绘图或保存绘图。

我使用内置数据集重新创建了您的情节,因为您共享的 onedrive 链接已损坏。我像这样使用了 Cambria 字体。

plot <- ggplot(dataset, aes(x = mpg, y = hp)) +
  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) +
  labs(x = "2019 GDP ($bn)", y = "2019 FDI ($m)") +
  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 = "Cambria")) # relevant line

我更喜欢将绘图保存在对象中并将其显式传递给保存函数。

ggsave(
  "FDI~GDP.png", 
  plot = plot, 
  device = ragg::agg_png, # this is the relevant part
  width = 1920, 
  height = 1080,
  units = "px"
) 

结果如下:

阴谋

我会说它完美无缺。您还可以ragg在 RStudio 中用作图形设备,以使其更加一致。看看这里

如果要将绘图输出为 PDF,可以使用showtext将系统字体注册到所有新打开的图形设备。所以你需要做的是:

library(showtext)
showtext_auto()
ggsave(
  "FDI~GDP.pdf", 
  plot = plot,
  width = 1920, 
  height = 1080,
  units = "px"
) 

推荐阅读