r - 在 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 链接
解决方案
我建议你看看包ragg
和systemfonts
. 它们使使用字体变得非常容易,并且结果比基本选项的输出要好。
首先,我建议您使用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"
)
推荐阅读
- asp.net-core - “访问 XMLHttpRequest 已被 CORS 策略阻止”即使我已允许所有源/标头/方法
- python - 如何在条件语句中使用嵌套在列表中的字典键值对的值?
- bcrypt - 无法在带有芯片 Apple M1 的 mac 上安装 bcrypto
- vba - JSON 和 getElementByID 什么都不返回
- c# - 如何在 C# 中将用户输入添加到二维数组
- aggregate - Vega 向数据添加静态字段
- python-3.x - 如何在 tmux 会话中使用 cron?
- delphi - 如何使用 div 功能
- python - Python:tqdm 进度条卡在 0%
- javascript - 使用复选框 onChange 在 React 中过滤卡片