1. 程式人生 > >用 matplotlib 畫圖無法顯示中文問題的根源及解決方案

用 matplotlib 畫圖無法顯示中文問題的根源及解決方案

用pandas 或者 matplotlib 畫圖時,遇到中文時會顯示出亂碼

matplotlib.png

分析其原因,matplotlib 初始化時首先要載入配置檔案,配置檔案的名字叫 matplotlibrc,字型設定也在這個配置檔案中,之所有無法正常顯示中文是因為 matplotlib 預設不支援中文字型,解決的辦法是我們需要在配置檔案中指定一個 matplotlib 可用的中文字型。

第一步:下載中文字型

SimHei.png

第二步:找到配置檔案 matplotlibrc

找到 matplotlib 載入的配置檔案路徑可以通過如下方式:

>>> import matplotlib
>>>
matplotlib.matplotlib_fname() '/Users/<USERNAME>/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc'

編輯 matplotlibrc 檔案,找到 font.family 和 font.sans-serif 這兩行,去掉註釋,並新增 SimHei 字型到 font.sans-serif 中,如下:

font.family         : sans-serif
font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

第三步:刪除緩衝目錄

rm -rf  ~/.matplotlib

第四步:重啟jupyter notebook

如果你是在 ipython 環境下畫圖就重啟 ipython,如果時 juypter notebook 畫圖 就重新 juypter notebook。


關注公眾號「Python之禪」(id:vttalk)獲取最新文章 python之禪