The matplotlib Chinese garbled solution in Python,
Matplotlib is a good drawing package for Python, but it does not support Chinese characters (it seems that there is no Chinese font in its default configuration), so if there is a Chinese character in the drawing, garbled characters will appear.
Matplotlib may cause garbled characters when the image is marked in Chinese.
Instance code:
Import matplotlibimport 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. 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 'decision point', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode (U 'leaf node ', (0.8, 0.1), (0.3, 0.8), leafNode) plt. show ()
Solution: Introduce the font in the code
Import matplotlib. pyplot as pltimport matplotlib # define the Custom font. The file name is the Chinese font of the system. myfont = matplotlib. font_manager.FontProperties (fname = 'C:/Windows/Fonts/simkai. ttf') # solve the problem that the negative sign '-' is displayed as a square 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 'decision point', (0.5, 0.1), (0.1, 0.5), decisionNode) plotNode (U 'leaf node ', (0.8, 0.1), (0.3, 0.8), leafNode) plt. show ()
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.