Rstudio-server、Rshiny-server、ggplot2中文乱码解决方法

  • Post author:
  • Post category:其他


气人的中文乱码

今天将R代码迁移到一个新的服务器上,之前用ggplot2画的图中文都是乱码,还弄了半天,就像下面的位置,现在已经处理好了。

本文记录一下这一次解决环境问题的乱码所用的方法。

安装环境

系统:unbuntu 16

R语言版本:3.4.4

方式一:直接安装中文字体

1、建立文件夹:/usr/shared/fonts/chinese

2、将windows的字体(c/windows/fonts)复制字体至文件夹中

3、 修改文件夹权限:chmod -R 755 /usr/share/fonts/chinese

4、mkfontscale(如果提示 mkfontscale: command not found,则需要安装# sudo apt-get install ttf-mscorefonts-installer)

5、mkfontdir

6、fc-cache -fv (如果提示 fc-cache: command not found,则需要安装# sudo apt-get install fontconfig)

这时画图可以直接通过family参数直接进行设置中文字体。

# 例如:
p = ggplot(plot_dat) + 
    geom_line(aes(x = date, y = freq, col = group)) + 
    geom_text(aes(x = date, y = freq, label = freq, group = group))
    theme(text = element_text(family = 'SimSun')) # 最后这个设置字体

字体的设置你可以通过,

fc-list :lang=zh-cn

命令来查看,下图的红色框框

这里写图片描述

方式二:全都设置成中文环境

配置linux locale

系统中文语言配置查看Ubuntu当前系统编码

locale如果不是以下中文的信息(而是英文en_US.UTF-8)

这里写图片描述

按照以下步骤配置中文环境:

1)安装中文

locale-gen zh_CN.UTF-8

2)修改为中文环境

update-locale LANG=zh_CN.UTF-8

3)查看是否修改成功

cat /etc/default/locale

4)设置成功后,重启机器

5) 再次打开Rstuido-server,画一个包含中文的图,测试

# 例如,不用再指定字体就可以直接显示中文了
p = ggplot(plot_dat) + 
    geom_line(aes(x = date, y = freq, col = group)) + 
    geom_text(aes(x = date, y = freq, label = freq, group = group))

测试结果,Rsudio-server中,中文直接显示成功!

这里写图片描述

方式三:用showtext包

很尴尬的是我的Rstudio-server中文乱码都已经解决了,但是在Rshiny-server中仍然显示乱码。

所以能使用,showtext包进行设置了

# 在整体上设置字体
library(showtext)
showtext_auto()
font.add("SimSun", "/usr/share/fonts/chinese/SIMSUN.TTC") # 你的中文字体位置

# 画个带中文的图
p = ggplot(plot_dat) + 
    geom_line(aes(x = date, y = freq, col = group)) + 
    geom_text(aes(x = date, y = freq, label = freq, group = group), family="SimSun", fontface="bold") 

这里写图片描述

更多关于 showtext包可以看这里


https://cosx.org/2014/01/showtext-interesting-fonts-and-graphs



版权声明:本文为qq_27755195原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。