如何解决R中保存绘图时中文显示异常的问题?
解决ggplot导出后中文消失的问题
这个问题核心是导出时未正确加载支持中文的字体,以下是两种可靠的解决方法:
方法1:使用ggsave()代码导出并指定中文字体
放弃RStudio界面的Export功能,直接用代码导出,同时明确指定系统支持的中文字体:
# 确保绘图对象已生成 tib.plot <- tib %>% ggplot(aes(x,y, label=character))+ geom_point()+ geom_label()+ geom_smooth(se=F)+ labs(x="Some Variable", y="Some Other Variable", title = "Simulated Plot")+ theme_classic() # 根据系统替换字体名后导出 # Windows系统用"SimHei",Mac用"PingFang SC",Linux用"Noto Sans CJK SC" ggsave("simulated_plot.png", plot = tib.plot, width = 8, height = 6, dpi = 300, family = "SimHei")
方法2:提前为ggplot全局设置中文字体
如果希望窗口显示和导出的字体统一,可以通过以下两种方式配置:
方式A:直接在theme中设置全局字体
tib.plot <- tib %>% ggplot(aes(x,y, label=character))+ geom_point()+ geom_label()+ geom_smooth(se=F)+ labs(x="Some Variable", y="Some Other Variable", title = "Simulated Plot")+ theme_classic()+ # 全局设置所有文本字体(包含标签、坐标轴、标题等) theme(text = element_text(family = "SimHei")) # 替换为对应系统的字体名
方式B:使用showtext包跨系统加载字体(更稳定)
先安装并加载showtext包,它能自动处理字体渲染,适合多系统场景:
install.packages("showtext") library(showtext) # 加载系统中已有的中文字体 font_add("my_font", "SimHei.ttf") # Windows # font_add("my_font", "PingFang SC.ttc") # Mac # font_add("my_font", "NotoSansCJKsc-Regular.otf") # Linux # 启用自动渲染 showtext_auto() # 绘图并导出 tib.plot <- tib %>% ggplot(aes(x,y, label=character))+ geom_point()+ geom_label()+ geom_smooth(se=F)+ labs(x="Some Variable", y="Some Other Variable", title = "Simulated Plot")+ theme_classic()+ theme(text = element_text(family = "my_font")) ggsave("simulated_plot.png", plot = tib.plot, width = 8, height = 6, dpi = 300)
注意事项
- 不同系统的字体名称存在差异,需替换为本地已安装的中文字体
- 可通过
windowsFonts()(Windows)、quartzFonts()(Mac)命令查看系统可用字体列表
内容的提问来源于stack exchange,提问作者Shawn Hemelstrand
相关产品推荐
相关产品推荐

