ggplot2中文乱码问题
之所以出现中文乱码是因为R环境只载入了三种英文字体,没有中文字体可用
解决办法就是从系统字体中载入中文字体,showtext包(会依赖sysfonts包)
library(showtext)
font_add("SmileySans", regular = "../data/SmileySans-Oblique-2.ttf") # regular参数填font文件的path
showtext_auto(enable = TRUE) # 自动启用
温馨提示,font是有版权的…
# 测试
library(ggplot2)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
labs(x = "引擎大小(L)", y = "高速燃油量(mpg)") +
theme(text = element_text(family = "SmileySans"))
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
xlab("排量") +
theme(axis.title.x = element_text(family = "SmileySans"))
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
scale_y_continuous(breaks = seq(15, 40, by = 10), labels = c("十五","二十五","三十五")) +
theme(axis.text.y = element_text(family = "SmileySans"))
如上,可以从“全局”层面对text设置,也可以对“局部”某处的text进行单独设置
P.S.
library(showtext)
showtext_auto(enable = TRUE) # 自动启用
不指定具体font,(不出意外的话)也可以解决中文乱码;
经个人测试,showtext里面是自带有中英文字体的(不确定哈)
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family 'SmileySans' not found, will use 'wqy-microhei' instead
showtext更重要作用可能在于解决 plot -> PDF 过程中的乱码问题
showtext makes it easy to use various types of fonts (TrueType,
OpenType, Type 1, web fonts, etc.) in R plots. The motivation to
develop this package is that using non-standard fonts in R plots
(especially for PDF device) is not straightforward, for example, when
creating PDF with Chinese characters. This is because most of the
standard fonts used by pdf() do not contain Chinese character glyphs,
and users could hardly use system fonts in R.
另外提一点,在rticles包的助力下,中文Rmd -> (Latex) -> PDF 也可以丝滑完成
最后
感谢Hadley,谢益辉等一众大佬的辛勤付出,让我拥有这些优秀的工具。感谢!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· c# 半导体/led行业 晶圆片WaferMap实现 map图实现入门篇
· 易语言 —— 开山篇