R 绘图 中文支持

不同系统的字体库目录:

  • Linux 一般在 /usr/share/fonts 下,我们可以使用 fc-list 命令查看:

    #fc-list/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf:DejaVuSerif:style=Bold/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf:DejaVuSansMono:style=Book/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:DejaVuSans:style=Book/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf:DejaVuSans:style=Bold/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf:DejaVuSansMono:style=Bold/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf:DejaVuSerif:style=Book
  • Windows 字体在 C:\Windows\Fonts\ 文件下,直接打开就能看到了。

  • mac OS 字体在 /System/Library/Fonts/Library/Fonts 目录下。

系统支持的字体库,可以通过安装 showtext 来查看:

>install.packages("showtext",repos="https://mirrors.ustc.edu.cn/CRAN/")#安装showtext...>font_files()#查看字体pathfilefamilyfaceversion1/Library/FontsArialUnicode.ttfArialUnicodeMSRegularVersion1.01xps_name1ArialUnicodeMS

看到有 ArialUnicodeMS,我们就可以用了:

pie3D(info,labels=names,explode=0.1,main="3D图",family="ArialUnicodeMS")

载入自定义字体

系统的字体库有时候不是支持的很好,showtext() 函数可以载入我们自定义的字体,可以下载字体包 ttf,然后使用 font_add() 函数添加。

这里我们使用思源黑体,思源黑体是 Adobe 与 Google 推出的一款开源字体。

官网:https://source.typekit.com/source-han-serif/cn/

GitHub 地址:https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese

打开链接后,在里面选一个就好了:

可以下载个 OTF 字体,比如 SourceHanSansSC-Bold.otf,将该文件文件放在当前执行的代码文件中:

柱形图使用字体库:

#载入showtextlibrary(showtext);#第一个参数设置字体名称,第二个参数为字体库路径,同目录下,我们写字体库名就可以了font_add("SyHei","SourceHanSansSC-Bold.otf");#设置文件名,输出为pngpng(file="nhooo-bar-cn.png")cvd19=c(83534,2640626,585493)#加载字体showtext_begin();barplot(cvd19,main="新冠疫情条形图",col=c("#ED1C24","#22B14C","#FFC90E"),names.arg=c("中国","美国","印度"),family='SyHei'#设置字体库)#去掉字体showtext_end();

图片.png

3D 饼图使用中文:

library(plotrix)library(showtext);#第一个参数设置字体名称,第二个参数为字体库路径,同目录下,我们写字体库名就可以了font_add("SyHei","SourceHanSansSC-Bold.otf");#数据准备info=c(1,2,4,8)#命名names=c("Google","Nhooo","Taobao","Weibo")#涂色(可选)cols=c("#ED1C24","#22B14C","#FFC90E","#3f48CC")#设置文件名,输出为pngpng(file="3d_pie_chart.png")#加载字体showtext_begin();#绘制3D图pie3D(info,labels=names,explode=0.1,main="3D图",family="SyHei")#去掉字体showtext_end();#关闭图形设备dev.off();

图片.png

编辑于2024-05-20 14:46