1. 程式人生 > >Matplotlib繪圖漢字不能正常顯示問題

Matplotlib繪圖漢字不能正常顯示問題

Python matplotlib繪圖,title、label和legend需要中文顯示,但matplotlib預設不支援中文,中文顯示亂碼。

解決辦法:
1.title、label,採用如下程式碼:

#-*- coding: utf-8 -*-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) 
plt.figure(figsize=(6
,6)) x = [1,2,3,4,5,6,7,8] y = [] for i in x: y.append(-(i*i)+i+3) plt.plot(x, y) plt.title(u'測試程式', fontproperties=font) plt.xlabel(u'x軸', fontproperties=font) plt.ylabel(u'y軸', fontproperties=font) plt.grid(True) plt.show()

2.legend,採用如下程式碼:

import matplotlib.pyplot as plt
import numpy as
np t = np.linspace(0, 10, 1000) y = np.sin(t) plt.plot(t, y,label=u'正弦曲線 (m)') plt.xlabel(u"時間", fontproperties='SimHei') plt.ylabel(u"振幅", fontproperties='SimHei') plt.title(u"正弦波", fontproperties='SimHei') # 新增單位 t=plt.text(6.25, -1.14,r'$(\mu\mathrm{mol}$'+' '+'$ \mathrm{m}^{-2} \mathrm{s}^{-1})$',fontsize=15
, horizontalalignment='center',verticalalignment='center') #在這裡設定是text的旋轉,0為水平,90為豎直 t.set_rotation(0) # legend中顯示中文 plt.legend(prop={'family':'SimHei','size':15}) plt.savefig("C:\\Users\\Administrator\\Desktop\\test.png")

3.其他
Matplotlib中支援LaTex語法,如果要顯示各種美觀的數學公式和數學符號,可以稍微學習下,很有用。具體語法可參見(http://wiki.gwrite.googlecode.com/hg/misc/LaTex-EquRef.html?r=1de19067fce5484bb5c39cbd049f6a47f7d8a2e9)
可以這樣使用:ylabel(‘Rice(‘+r’μmol’+’ ‘+’m2s1’+’)’)。

中文與LaTex共同顯示問題:
在座標軸標題中同時顯示中文以及帶有上下標的各種數學單位,需要分兩步:
1、根據上述顯示中文的方法,先將中文標題加上;
2、對於單位,使用text函式進行新增,text函式用法見(http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text)。