【轉】 Python 中,matplotlib繪圖無法顯示中文的問題

來源:互聯網
上載者:User

標籤:決策   creat   ota   span   ref   ax1   erp   mat   detail   

在python中,預設情況下是無法顯示中文的,如下代碼:

[python] view plain copy 
  1. import matplotlib.pyplot as plt  
  2.   
  3. # 定義文字框和箭頭格式  
  4. decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")  
  5. leafNode = dict(boxstyle = "round4", fc = "0.8")  
  6. arrow_args = dict(arrowstyle = "<-")  
  7.   
  8. # 繪製帶箭頭的註解  
  9. def plotNode(nodeTxt, centerPt, parentPt, nodeType) :  
  10.     createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = ‘axes fraction‘, xytext = centerPt, textcoords = ‘axes fraction‘, va = ‘center‘, ha = ‘center‘, bbox = nodeType, arrowprops = arrow_args)  
  11.   
  12. def createPlot() :  
  13.     fig = plt.figure(1, facecolor=‘white‘)  
  14.     fig.clf()  
  15.     createPlot.ax1 = plt.subplot(111, frameon = False)  
  16.     plotNode(U‘決策節點‘, (0.5, 0.1), (0.1, 0.5), decisionNode)  
  17.     plotNode(U‘分葉節點‘, (0.8, 0.1), (0.3, 0.8), leafNode)  
  18.     plt.show()  
  19.   
  20. createPlot()  

 

得到映像如下:

 

產生中文亂碼的原因就是字型的預設設定中並沒有中文字型,所以我們只要手動添加中文字型的名稱就可以了

手動增加如下代碼

 

[python] view plain copy 
  1. from pylab import *  
  2. mpl.rcParams[‘font.sans-serif‘] = [‘SimHei‘]  


原始碼修改如下:

 

 

[python] view plain copy 
  1. import matplotlib.pyplot as plt  
  2.   
  3. from pylab import *  
  4. mpl.rcParams[‘font.sans-serif‘] = [‘SimHei‘]  
  5.   
  6. # 定義文字框和箭頭格式  
  7. decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")  
  8. leafNode = dict(boxstyle = "round4", fc = "0.8")  
  9. arrow_args = dict(arrowstyle = "<-")  
  10.   
  11. # 繪製帶箭頭的註解  
  12. def plotNode(nodeTxt, centerPt, parentPt, nodeType) :  
  13.     createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = ‘axes fraction‘, xytext = centerPt, textcoords = ‘axes fraction‘, va = ‘center‘, ha = ‘center‘, bbox = nodeType, arrowprops = arrow_args)  
  14.   
  15. def createPlot() :  
  16.     fig = plt.figure(1, facecolor=‘white‘)  
  17.     fig.clf()  
  18.     createPlot.ax1 = plt.subplot(111, frameon = False)  
  19.     plotNode(U‘決策節點‘, (0.5, 0.1), (0.1, 0.5), decisionNode)  
  20.     plotNode(U‘分葉節點‘, (0.8, 0.1), (0.3, 0.8), leafNode)  
  21.     plt.show()  
  22. createPlot()  

最終得到映像

 

 

成功!

原文連結:http://blog.csdn.net/u013038499/article/details/52449768

【轉】 Python 中,matplotlib繪圖無法顯示中文的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.