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


在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM