ggplot2中柱形图标签字体未生效,轴标签正常的解决方法
解决ggplot2中geom_text标签不继承主题字体的问题
问题分析
你通过theme_bw(base_family = "LM Roman 10")设置了全局主题字体,但柱形上方的geom_text标签仍使用默认字体,核心原因是geom_text作为独立的几何图层,默认不会自动继承主题的base_family参数,需要单独指定或全局配置默认值。
另外要确保extrafont的字体加载流程正确,否则即使指定字体也可能不生效:
- 首次使用extrafont时需运行
font_import()(仅需执行一次,耗时较长) - 每次R会话启动时运行
loadfonts()加载字体
解决方案
方法1:直接在geom_text中指定字体
修改geom_text代码,添加family = "LM Roman 10"参数,与主题字体保持一致:
ggplot(data, aes(x = Year, y = Value)) + geom_col(fill = "#7f7f7f", width = 0.5) + geom_text(aes(label = format(Value, big.mark = '.', scientific = FALSE)), position = position_dodge(width = 0.9), size = 3.5, colour = 'black', vjust = -0.5, family = "LM Roman 10") + scale_y_continuous(limits = c(0, 10000), labels = scales::comma_format(big.mark = '.')) + scale_x_continuous(name = "Year", limits = c(2009.5, 2021.5), breaks = seq(2010, 2021, by = 1)) + labs(x = NULL, y = "Number of Units", title = NULL) + theme_bw(base_size = 14, base_family = "LM Roman 10") + theme(legend.position = "none", panel.grid = element_blank())
方法2:全局设置geom_text默认字体
如果需要多个图表统一geom_text的字体,可在代码开头用update_geom_defaults()设置全局默认值,后续所有geom_text都会自动使用该字体:
# 全局配置geom_text的默认字体 update_geom_defaults("text", list(family = "LM Roman 10")) # 正常绘制图表,无需再给geom_text单独指定family参数 ggplot(data, aes(x = Year, y = Value)) + geom_col(fill = "#7f7f7f", width = 0.5) + geom_text(aes(label = format(Value, big.mark = '.', scientific = FALSE)), position = position_dodge(width = 0.9), size = 3.5, colour = 'black', vjust = -0.5) + scale_y_continuous(limits = c(0, 10000), labels = scales::comma_format(big.mark = '.')) + scale_x_continuous(name = "Year", limits = c(2009.5, 2021.5), breaks = seq(2010, 2021, by = 1)) + labs(x = NULL, y = "Number of Units", title = NULL) + theme_bw(base_size = 14, base_family = "LM Roman 10") + theme(legend.position = "none", panel.grid = element_blank())
验证注意事项
- 若使用RStudio,有时需重启R会话或重新加载字体才能看到效果
- 可通过
fonts()命令查看extrafont已加载的字体列表,确认"LM Roman 10"在列表中
内容的提问来源于stack exchange,提问作者pbraeutigm
相关产品推荐
相关产品推荐

