【发布时间】:2019-02-23 00:22:26
【问题描述】:
我正在 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 控制台中也没有看到任何错误或警告。
【问题讨论】:
-
showtext不适用于 RStudio 图形设备 github.com/yixuan/showtext/issues/7 -
您可以下载“Pragati Narrow”字体并尝试使用
extrafont包吗? stackoverflow.com/a/51888677 -
@Tung 谢谢。我确实注意到 RStudio 的查看器不适用于
showtext。但是下载“Pragmati Narrow”会改变ggsave()的输出吗?我也不确定如何在我的计算机上安装该字体。我正在使用 Debian 9.3 -
它应该可以工作。按照我上面链接的答案中的步骤进行操作。我之前在 Windows 和 Linux 上都测试过
-
查看我的答案以获取工作示例
标签: r ggplot2 fonts showtext extrafont