Matplotlib是Python的一個很好的繪圖包,但是其本身并不支持中文(貌似其默認配置中沒有中文字體),所以如果繪圖中出現了中文,就會出現亂碼。
matplotlib繪制圖像有中文標注時會有亂碼問題。
實例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import matplotlib 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.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() |
解決辦法:代碼中引入字體
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import matplotlib.pyplot as plt import 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() |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/f8c9d04e537e