首页 > 解决方案 > 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 控制台中看到任何错误或警告。

标签: rggplot2fontsshowtextextrafont

解决方案


这适用于我的 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)

在此处输入图像描述


推荐阅读