Python 中,matplotlib绘图无法显示中文的问题
生活随笔
收集整理的這篇文章主要介紹了
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 pltfrom 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()
最終得到圖像
成功!
總結
以上是生活随笔為你收集整理的Python 中,matplotlib绘图无法显示中文的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习Tensorflow基础知识、张
- 下一篇: Kaggle 房价预测竞赛优胜方案:用