ubuntu 下在 matplotlib 中正常显示中文的解决办法

ubuntu 下在 matplotlib 中正常显示中文的解决办法

首先, 确认你 ubuntu 系统环境下拥有的中文字体文件:

~$ fc-list :lang=zh

然后,在 python 脚本中手动加载中文字体,加载方法就是在相应命令中加入 fontproperties=zhfont 属性的赋值字体路径来自与”1”中返回的结果(从其中挑选出一种能够显示中文的字体即可)
测试程序如下:

from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib as mpl

zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc')

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, fontproperties=zhfont)

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()

运行结果如下:
ubuntu 下在 matplotlib 中正常显示中文的解决办法_第1张图片

你可能感兴趣的:(Python)