Python 中,matplotlib绘图无法显示中文的问题

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站 在python中,默认情况下是无法显示中文的,如下代码:

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.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()	createPlot.ax1 = 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() createPlot()

得到图像如下:

产生中文乱码的原因就是字体的默认设置中并没有中文字体,所以我们只要手动添加中文字体的名称就可以了

手动增加如下代码

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

源代码修改如下:

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()	createPlot.ax1 = 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()createPlot()

最终得到图像

成功!

点这里可以跳转到人工智能网站

发表评论