Python uses matplotlib to plot and cannot display Chinese characters,
This example describes how to solve the problem that matplotlib cannot display Chinese Characters in Python. We will share this with you for your reference. The details are as follows:
In python, Chinese characters cannot be displayed by default, as shown in the following code:
Import matplotlib. pyplot as plt # define text box and arrow format decisionNode = dict (boxstyle = "sawtooth", fc = "0.8") leafNode = dict (boxstyle = "round4 ", fc = "0.8") arrow_args = dict (arrowstyle = "<-") # Draw the arrow annotation 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 'decision node', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode (U 'leaf node ', (0.8, 0.1), (0.3, 0.8), leafNode) plt. show () createPlot ()
The image is as follows:
The reason for Chinese garbled characters is that there is no Chinese font in the default font settings, so we only need to manually add the Chinese font name.
Manually Add the following code
from pylab import *mpl.rcParams['font.sans-serif'] = ['SimHei']
The source code is modified as follows:
Import matplotlib. pyplot as pltfrom pylab import * mpl. rcParams ['font. sans-serif'] = ['simhei'] # define the text box and arrow format decisionNode = dict (boxstyle = "sawtooth", fc = "0.8 ") leafNode = dict (boxstyle = "round4", fc = "0.8") arrow_args = dict (arrowstyle = "<-") # Draw annotation 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 'decision node', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode (U 'leaf node ', (0.8, 0.1), (0.3, 0.8), leafNode) plt. show () createPlot ()
Final Image
Successful!