安装libpng:
sudo yum install libpng-devel
在安装完上述包之后,再用pip install就好。
需要的包:
import matplotlib
matplotlib.use('Agg') #不出现画图的框
from flask import Flask
app = Flask(__name__)
from io import BytesIO
import os
import base
画图的函数:
def plotTree(s):
fig = plt.figure(1,figsize=(12,6),facecolor='white')
....#一系列画图操作
return fig
flask的函数:
@app.route('/', methods=['GET']) #传入参数
def index(name):
fig=plotTrees(name)
# Encode image to png in base
sio = BytesIO()
fig.savefig(sio, format='png')
data=base.encodebytes(sio.getvalue()).decode()
return html.format(data)
main函数:
if __name__ == '__main__':
html = '''
< img src="data:image/png;base,{}" />
app.run(port=7000,debug=True,threaded=False)
在上述两步完成以后,其实已经在网页上显示图片了,但是由于matplotlib默认字体不支持中文,所以的中文字都变成了框框。有两种方法解决:
1. mac上成功解决的方法:
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体
mpl.rcParams['axes.unicode_minus'] = False #解决保存图像是负号'-'显示为方块的问题
2. 该方法我在linux上没成功,研究半天没搞明白为啥,不过还好有另外的方法
1)首先在linux找系统的中文字体的.ttc文件
fc-list
如果不幸发现linux上没有中文字体,没事,将自己电脑上的字体复制到linux上就行,linux上字体放在/usr/share/fonts上。
2)然后在python中加入代码,表示matplotlib用该字体,比如我找的是wqy-zenhei/wqy-zenhei.ttc, 那么在python中加入
myfont = FontProperties(fname='/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc’)
然后在所有画图中添加字体的函数中,加入 fontproperties=myfont,然后就ok拉。
最后展示下很简单的结果:
后续有时间的话,会加入互动功能,让检查人员能反馈给我,哪条路径是错的,哪个node是错的,哪个叶子结果是错的等功能。
下载本文