Python使用matplotlib繪圖無法顯示中文問題的解決方法
本文實例講述了Python使用matplotlib繪圖無法顯示中文問題的解決方法。分享給大家供大家參考,具體如下:
在python中,默認情況下是無法顯示中文的,如下代碼:
import matplotlib.pyplot as plt # 定義文本框和箭頭格式 decisionNode = dict(boxstyle = "sawtooth", fc = "0.8") leafNode = dict(boxstyle = "round4", fc = "0.8") arrow_args = dict(arrowstyle = "<-") # 繪制帶箭頭的注解 def plotNode(nodeTxt, centerPt, parentPt, nodeType) : createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = 'axes fraction', xytext = centerPt, textcoords = 'axes fraction', va = 'center', ha = 'center', bbox = nodeType, arrowprops = arrow_args) def createPlot() : fig = plt.figure(1, facecolor='white') fig.clf() createPlot.ax1 = plt.subplot(111, frameon = False) plotNode(U'決策節(jié)點', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode(U'葉節(jié)點', (0.8, 0.1), (0.3, 0.8), leafNode) plt.show() createPlot()
得到圖像如下:

產(chǎn)生中文亂碼的原因就是字體的默認設(shè)置中并沒有中文字體,所以我們只要手動添加中文字體的名稱就可以了
手動增加如下代碼
from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei']
源代碼修改如下:
import matplotlib.pyplot as plt from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei'] # 定義文本框和箭頭格式 decisionNode = dict(boxstyle = "sawtooth", fc = "0.8") leafNode = dict(boxstyle = "round4", fc = "0.8") arrow_args = dict(arrowstyle = "<-") # 繪制帶箭頭的注解 def plotNode(nodeTxt, centerPt, parentPt, nodeType) : createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = 'axes fraction', xytext = centerPt, textcoords = 'axes fraction', va = 'center', ha = 'center', bbox = nodeType, arrowprops = arrow_args) def createPlot() : fig = plt.figure(1, facecolor='white') fig.clf() createPlot.ax1 = plt.subplot(111, frameon = False) plotNode(U'決策節(jié)點', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode(U'葉節(jié)點', (0.8, 0.1), (0.3, 0.8), leafNode) plt.show() createPlot()
最終得到圖像

成功!
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)學(xué)運算技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
基于python的漢字轉(zhuǎn)GBK碼實現(xiàn)代碼
今天想用python調(diào)用百度框計算的搜過結(jié)果,看到了URL里面的漢字用GBK編碼,雖然可以直接在URL里面加入中文,之前也做過一個簡體字轉(zhuǎn)GBK碼的python函數(shù),但還是略嫌麻煩,今天改了一下2012-02-02
Python Django form 組件動態(tài)從數(shù)據(jù)庫取choices數(shù)據(jù)實例
這篇文章主要介紹了Python Django form 組件動態(tài)從數(shù)據(jù)庫取choices數(shù)據(jù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python實現(xiàn)字符串模糊匹配的兩種實現(xiàn)方法
本文主要介紹了Python實現(xiàn)字符串模糊匹配的兩種實現(xiàn)方法,Python中通過re.search()方法實現(xiàn),對于首位起始的內(nèi)容匹配,也可通過re.match()方法實現(xiàn),感興趣的可以了解一下2023-11-11
使用python把Excel中的數(shù)據(jù)在頁面中可視化
最近學(xué)習(xí)數(shù)據(jù)分析,感覺Python做數(shù)據(jù)分析真的好用,下面這篇文章主要給大家介紹了關(guān)于如何使用python把Excel中的數(shù)據(jù)在頁面中可視化的相關(guān)資料,需要的朋友可以參考下2022-03-03
python中使用 xlwt 操作excel的常見方法與問題
這篇文章主要給大家介紹了關(guān)于python中使用 xlwt 操作excel的常見方法與問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01

