r - ggsave() 不会加粗文本,它会更改所有文本的字体,而不仅仅是绘图标题
问题描述
我正在 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
)
我期望图表的标题具有自定义字体。相反,ggsave()
制作一个所有文本都有字体的图表。我希望轴标题是粗体的,但事实并非如此。
这是我在 RStudio 查看器中运行ggplot()
代码时看到的内容。
这就是ggsave()
产生的东西。
我想ggsave()
制作一个图表,其中只有图表的标题有字体,轴的标题是粗体的。
更新:我尝试了 Tung 的建议。我把谷歌字体下载到我的电脑上。这是我的新代码。
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
)
似乎什么都没有改变。
我也没有在 RStudio 控制台中看到任何错误或警告。
解决方案
这适用于我的 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)
推荐阅读
- sql - SQL - 从多个表中获取关联数据
- vba - 如何删除输出文件中标题名称中的空格
- android - 如何从字符串“October”和整数值“2018”获取完整日期格式为完整日期格式?
- python - 许多小部件分别堆叠 QTableWidgets 的性能问题
- javascript - 从 JS 中的子网生成随机 IP 地址
- python - 完全模仿 tkinter 文本小部件中的标准输出,以支持 Python 打印函数中的 end 参数
- spring - 在运行时停止 Spring @Controller
- robotframework - 如何在 Robot Framework 中将 Dictionary 转换为 String 或 StringBuffer?
- php - 如何从未链接到其他表的表中选择行?
- javascript - 如果我断开连接,Trello API 身份验证不会提供有效的用户令牌