Python中matplotlib绘图plotNode()函数无法显示汉字问题解决

如上图所示是使用机器学习实战附带源码,在python上的得到的plotNode()函数输出,显然,'决策节点'和'叶节点'这两行汉字未能显示

产生中文乱码的原因:字体的默认设置中无中文字体,需要手动添加中文字体的名称

添加代码如下:

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

注意:官方自带源码中还需要对createPlot.ax1.annotate()函数进行修改
修改后源码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 30 15:57:37 2018

@author: demons
"""
import matplotlib.pyplot as plt
from pylab import *  
mpl.rcParams['font.sans-serif'] = ['SimHei']  

#定义文本框和箭头格式
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.ax1.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()
#    axprops = dict(xticks=[], yticks=[])
#    createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)    #no ticks
    createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses  
#    plotTree.totalW = float(getNumLeafs(inTree))
#    plotTree.totalD = float(getTreeDepth(inTree))
#    plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
#    plotTree(inTree, (0.5,1.0), '')
    plotNode(U'决策节点',(0.5,0.1),(0.1,0.5),decisionNode)
    plotNode(U'叶节点',(0.8,0.1),(0.3,0.8),leafNode)
    plt.show()

最终效果图:

猜你喜欢

转载自blog.csdn.net/weixin_41797117/article/details/79759767
今日推荐