Matplotlib是Python的一個很好的繪圖包,但是其本身并不支持中文(貌似其默認配置中沒有中文字體),所以如果繪圖中出現了中文,就會出現亂碼。
python/267132.html">matplotlib繪制圖像有中文標注時會有亂碼問題。

實例代碼:
import matplotlibimport 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.axl.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.axl=plt.subplot(111,frameon=False) plotNode(U'決策點',(0.5,0.1),(0.1,0.5),decisionNode) plotNode(U'葉節點',(0.8,0.1),(0.3,0.8),leafNode) plt.show()
解決辦法:代碼中引入字體
import matplotlib.pyplot as pltimport matplotlib#定義自定義字體,文件名是系統中文字體myfont = matplotlib.font_manager.FontProperties(fname='C:/Windows/Fonts/simkai.ttf') #解決負號'-'顯示為方塊的問題 matplotlib.rcParams['axes.unicode_minus']=False 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.axl.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',xytext=centerPt,textcoords='axes fraction',va="center",ha="center",bbox=nodeType,arrowprops=arrow_args,fontproperties=myfont)def createPlot(): fig =plt.figure(1,facecolor='white') fig.clf() createPlot.axl=plt.subplot(111,frameon=False) plotNode(U'決策點',(0.5,0.1),(0.1,0.5),decisionNode) plotNode(U'葉節點',(0.8,0.1),(0.3,0.8),leafNode) plt.show()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答