1. 程式人生 > >Python matplotlib繪圖無法顯示中文的問題

Python matplotlib繪圖無法顯示中文的問題

在python中,預設情況下是無法顯示中文的,如下程式碼:
  1. import matplotlib.pyplot as plt
  2. # 定義文字框和箭頭格式
  3. decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")
  4. leafNode = dict(boxstyle = "round4", fc = "0.8")
  5. arrow_args = dict(arrowstyle = "<-")
  6. # 繪製帶箭頭的註解
  7. def plotNode(nodeTxt, centerPt, parentPt, nodeType) :
  8. createPlot.ax1.annotate(nodeTxt, xy = parentPt, xycoords = 'axes fraction'
    , xytext = centerPt, textcoords = 'axes fraction', va = 'center', ha = 'center', bbox = nodeType, arrowprops = arrow_args)
  9. def createPlot() :
  10. fig = plt.figure( 1, facecolor= 'white')
  11. fig.clf()
  12. createPlot.ax1 = plt.subplot( 111, frameon = False)
  13. plotNode(U '決策節點', ( 0.5, 0.1), ( 0.1, 0.5), decisionNode)
  14. plotNode(U '葉節點', ( 0.8, 0.1), ( 0.3, 0.8), leafNode)
  15. plt.show()
  16. createPlot()

得到影象如下:


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

手動增加如下程式碼

  1. from pylab import *
  2. mpl.rcParams[ 'font.sans-serif'] = [ 'SimHei']

原始碼修改如下:
  1. import matplotlib.pyplot as plt
  2. from pylab import *
  3. mpl.rcParams[ 'font.sans-serif'] = [ 'SimHei']
  4. # 定義文字框和箭頭格式
  5. decisionNode = dict(boxstyle = "sawtooth", fc = "0.8")
  6. leafNode = dict(boxstyle = "round4", fc = "0.8")
  7. arrow_args = dict(arrowstyle = "<-")
  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. def createPlot() :
  12. fig = plt.figure( 1, facecolor= 'white')
  13. fig.clf()
  14. createPlot.ax1 = plt.subplot( 111, frameon = False)
  15. plotNode(U '決策節點', ( 0.5, 0.1), ( 0.1, 0.5), decisionNode)
  16. plotNode(U '葉節點', ( 0.8, 0.1), ( 0.3, 0.8), leafNode)
  17. plt.show()
  18. createPlot()
最終得到影象

完成!