1. 程式人生 > >matplotlib座標軸中文亂碼問題解決

matplotlib座標軸中文亂碼問題解決

用了一晚上時間一直在搞這個問題,網上解決方法眾多,沒有一個實用的,最後終於解決了。
系統: win10
環境: VS Code1.16
python 2.7.13

方法

  • 找到matplotlib的配置檔案位置
import matplotlib 
print(matplotlib.matplotlib_fname())
#我這裡的位置是C:\Python27\lib\site-packages\matplotlib\mpl-data\matplotlibrc
  1. 開啟matplotlibrc檔案進行編輯,找到#font.family : sans-serif

    更改為: font.family : SimHei

  2. -號會顯示出錯的解決方法為:
    在配置檔案裡找到#axes.unicode_minus : True更改為:axes.unicode_minus : False

測試程式碼:

coding:utf-8
from numpy import*
import matplotlib.pyplot as plt

x = linspace(0,4*pi,1000)
y = sin(x)
plt.title(u'matplotlib中文圖例顯示')
plt.plot(x,y,'b',label = u"橫軸sin(x)", color = "red"
) plt.xlim(0,4*pi) plt.ylim(-1,1) plt.xlabel(u'橫軸x') plt.ylabel(u'縱軸y') plt.legend() plt.show()

這裡寫圖片描述

注意:

  1. 開頭要加上#coding:utf-8,否則還是亂碼
  2. 中文前要加上u來轉換編碼

參考了這裡的內容: