You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot设置字体为Times New Roman失效如何解决?附现有调试代码

ggplot设置Times New Roman字体失效解决方法
  • 第一步:注册系统字体到R环境
    ggplot默认无法直接调用系统安装的字体,需要先通过extrafont包完成字体注册:
# 安装依赖包(仅首次运行需要)
install.packages("extrafont")
library(extrafont)
# 导入系统全部字体,首次运行耗时3-5分钟,请等待执行完成
font_import()
# 查看已识别字体列表,确认Times New Roman在返回结果中
fonts()

Linux系统用户需要先安装微软核心字体包后再执行上述操作,Ubuntu/Debian可通过命令sudo apt install ttf-mscorefonts-installer安装字体。

  • 第二步:完善主题字体配置
    仅设置全局text属性可能存在部分元素继承失效的问题,可补充各细分文本元素的字体配置:
# 调整后的完整绘图代码示例
Dallasdeck_infex <- ggplot(Alldata, aes(Date)) + 
  geom_tile(aes(alpha = Recession, y = 1), fill = "grey", height = Inf) + 
  scale_alpha_continuous(range = c(0, 1), breaks = c(0, 1), labels = c("0" = "Expansion", "1" = "Recession"))+ 
  geom_line(aes(y = INFEX), col = "blue", size = .8)+ 
  ylab('Inflation Expectations (%)')+ 
  labs(x = NULL, alpha = "Economic Cycle", color = "Economic Variable",
       title = "Rising Inflation Expectations in 2021",
       caption = 'Cleveland Fed Model of 10-year Inflation Expectations',
       subtitle = '"Directionality Matters"')+ 
  theme(plot.background = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major= element_blank(),
        text = element_text(color = "#CC0E44", family = "Times New Roman"),
        # 补充细分元素字体设置
        axis.text = element_text(family = "Times New Roman"),
        plot.title = element_text(family = "Times New Roman"),
        plot.subtitle = element_text(family = "Times New Roman"),
        plot.caption = element_text(family = "Times New Roman"),
        legend.text = element_text(family = "Times New Roman")) 
Dallasdeck_infex

注:原代码中Economic Cylcle存在拼写错误,已修正为Economic Cycle。

  • 第三步:导出文件时保留字体
    如果导出PDF时出现字体丢失问题,使用cairo图形设备导出即可:
ggsave("通胀预期趋势图.pdf", plot = Dallasdeck_infex, device = cairo_pdf, dpi = 300)

内容的提问来源于stack exchange,提问作者MacroChair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:54:05