天天看點

Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題

Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題

中文亂碼問題示例

使用

matplotlib.pyplot

畫圖時,需要在圖示題、軸标題處使用中文,用以下代碼畫出來的圖會出現亂碼,如下圖所示。

t = np.linspace(0, 2*np.pi, 100)
y = np.sin(t)

plt.plot(t, y)
plt.title(u"正弦信号")
plt.xlabel(u"時間")
plt.ylabel(u"幅度")
           
Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題

解決方案

在開頭加如下代碼。其中,第一句的

'Droid Sans Fallback'

是Ubuntu自帶的漢字字型,第二句的作用是正常顯示負号。

matplotlib.rcParams['font.sans-serif'] = ['Droid Sans Fallback']
matplotlib.rcParams['axes.unicode_minus']=False
           
Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題Ubuntu解決matplotlib.pyplot的title和label中文亂碼問題

Reference

matplotlib繪圖之中文标題、坐标軸标簽亂碼問題

Windows系統下最簡單方式解決python matplotlib中文亂碼問題

matplotlib.pyplot中文标題亂碼

matplotlib教程之——自定義配置檔案和繪圖風格(rcParams和style)

[StackOverFlow] How to load .ttf file in matplotlib using mpl.rcParams?

Python繪圖問題:Matplotlib中rcParams使用

繼續閱讀