Use*_*ame 8 fonts r ggplot2 showtext extrafont
我正在 ggplot2 中制作图表,但ggsave()没有达到我的预期。
require(ggplot2)
require(showtext)
showtext_auto()
hedFont <- "Pragati Narrow"
font_add_google(
name = hedFont,
family = hedFont,
regular.wt = 400,
bold.wt = 700
)
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = hedFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
ggsave(
filename = "myplot",
plot = chart,
device = "png",
path = "~/Desktop",
width = 300,
height = 200,
units = "mm",
dpi = 72
)
Run Code Online (Sandbox Code Playgroud)
我期望图表的标题具有自定义字体。相反,ggsave()制作一个所有文本都具有字体的图表。我希望轴标题是粗体的,但事实并非如此。
以下是我在 RStudio 查看器中运行ggplot()代码时看到的内容。
这是ggsave()产生的结果。
我想ggsave()制作一个图表,其中只有图表的标题具有字体,并且轴的标题为粗体。
更新:我尝试了Tung的建议。我将 Google 字体下载到我的计算机上。这是我的新代码。
font_import(
paths = "/usr/share/fonts/truetype/google-fonts/",
recursive = T,
prompt = F,
pattern = "Pragati"
)
loadfonts(device = "pdf")
loadfonts(device = "postscript")
myFont <- "Pragati Narrow"
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = myFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
ggsave(
filename = "myplot2.png",
plot = chart,
device = "png",
path = "~/Desktop",
width = 300,
height = 200,
units = "mm",
dpi = 72
)
Run Code Online (Sandbox Code Playgroud)
似乎没有改变什么。
我在 RStudio 控制台中也没有看到任何错误或警告。
小智 6
我在使用该包时遇到了类似的问题extrafont,我指定的字体将显示在 RStudio 查看器中,但当我保存.png为ggsave(). 上述两个答案都不适合我(字体已经保存在我的extrafont数据库中并且指定base_family不起作用)。
ragg我只需使用 卸载软件包即可使其正常工作installr::uninstall.packages("ragg")。
我不知道为什么会这样,如果有人对此有任何解释,我很想听听。
这在我的 Linux Mint Rosa 机器上有效。您需要extrafont根据此答案下载所需的字体并将其导入数据库
library(extrafont)
library(ggplot2)
hedFont <- "BitstreamVeraSansMono"
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = hedFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
chart
ggsave(
filename = "./output/myplot.png",
plot = chart,
type = "cairo",
height = 4,
width = 6,
dpi = 150)
Run Code Online (Sandbox Code Playgroud)