解決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環境)

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