解决linux与Windows系统中matplotlib和seaborn画图时中文乱码问题(实测有效)。

运行环境:

  • python3.7
  • Linux Centos7
  • 用conda安装的matplotlib与seaborn

问题:

  • matplotlib与seaborn画图,无法正常显示中文

问题原因:

  • linux操作系统以及matplotlib的字体库中,没有可用的中文字体
  • matplotlib包默认只支持ASCII码,不支持unicode码

解决方法

 

方法一(matplotlib与seaborn都能解决):

安装中文字体,并加入matplotlib配置文件中,配置步骤如下:

  1. 到 anaconda 的 matplotlib 中查看是否有 simhei.ttf 字体。
    cd ~/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf
    ls -al | grep simhei 

     

  2. 如果没有,从 windows C:\Windows\Fonts中找到 simhei.ttf,并将其上传到linux 的 matplotlib 的 fonts/ttf 文件夹
  3. 修改配置文件~/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc 文件,修改方式如下:
    vim /opt/app/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
    
    #修改下述两行
    #此行取消注释即可
    font.family         : sans-serif
    #此行,取消注释后添加新加入的simhei字体名称
    font.sans-serif     : simhei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

     

  4. 将该文件拷贝到.cache/matplotlib 目录下,并删除matplotlib 下的fontList.josn文件(重新启动python文件后会重新生成)。
  5. 在画图时,显式的设置画图时的字体类型。以下是示例:
    import matplotlib as mpl
    import matplotlib.pyplot as plt  
    mpl.rcParams['font.sans-serif'] = ['simhei']
    mpl.rcParams['font.serif'] = ['simhei']
    import seaborn as sns
    sns.set_style("darkgrid",{"font.sans-serif":['simhei','Droid Sans Fallback']})
    import pandas as pd 
    temp=pd.read_csv("/opt/temp.txt",header=None)
    temp.head()

     

 

方法二(只能解决matplotlib中):

在linux系统中安装一个可用的中文字体,安装过程如下所示:

  1. 安装那种系统能检测font-family的,否则无效。我在这个网站下载的:http://font.chinaz.com/130130474870.htm
  2. 将解压文件中的ttf文件复制到linux系统。我的位置为/usr/share/fonts 路径下的新建文件夹myfonts(可以给文件改个英文名,方便操作)。
  3. 给cenos安装这个字体。
    先:
        yum install -y fontconfig mkfontscale
    
    然后:
        cd  /usr/share/fonts/myfonts
    
    #生成字体索引信息. 会显示字体的font-family
    
        sudo mkfontscale
    
        sudo mkfontdir
    
    #更新字体缓存:
    
        fc-cache

     

使用示例

在使用时显示的给与字体的位置信息,示例代码如下:

from matplotlib.font_manager import FontProperties  
import matplotlib.pyplot as plt  
font = FontProperties(fname="/usr/share/fonts/myfonts/chinese.ttf", size=14)  
plt.xlabel(u"电压差(V)", fontproperties=font)  
plt.ylabel(u"介质损耗角差(度)", fontproperties=font)  
plt.title(u"介质损耗角和荷电状态SOC关系图",fontproperties=font) 
plt.show()

备注:此方法每次需要都需要导入画图中的中文字体路径。

 

运行环境:

  • python3.7
  • win10
  • 用conda安装的matplotlib与seaborn

解决方法(直接显式指定字体):

代码:

import matplotlib.pyplot as plt  
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
import seaborn as sns
sns.set_style("darkgrid",{"font.sans-serif":['simhei', 'Arial']})
ax = sns.barplot(x=1, y=0, data=temp)
plt.show()

 

参考博客:

博客一,方法一的参考博客

方法二中的参考博客

python matplotlib如何显示中文(window环境)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章