#!/usr/bin/env python
#-*- coding: utf-8 -*-
#使用matplotlib的版本为0.5.11,安装方式 pip install matplotlib==0.5.11
import matplotlib
matplotlib.use('Agg') #linux环境下使用,在matplotlib.pyplot导入前,否则会出现_tkinter.TclError: no display name and no $DISPLAY environment variable 错误
from pylab import * #通过这种方式导入,可以直接用pie画图,否则用pyplot.pie画图
from matplotlib import pyplot as plt
from io import BytesIO
from lxml import etree
import base64
plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码,linux环境下需要增加simhei.ttf
matplotlib.rcParams['font.family']='sans-serif'
#解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus'] = False
def draw_pie(sizes,labels):
figure(figsize=(6, 9)) #调节图形大小
pie(sizes,
labels=labels,
autopct='%3.2f%%', # 数值保留固定小数位
startangle=90 # 逆时针起始角度设置
)
axis('equal') # x,y轴刻度设置一致,保证饼图为圆形
legend() #显示标签
buffer = BytesIO()
savefig(buffer) #保存为二进制
#savefig("pie.png") #保存为图片
plot_data = buffer.getvalue()
imb = base64.b64encode(plot_data)
ims = imb.decode()
imd = "data:image/png;base64," + ims
res = """<br/><img src="%s">""" % imd
close()
return res
labels = [u'大型:46个',u'中型:253个',u'小型:321个',u'微型:66个'] #定义标签
sizes = [46,253,321,66] #每块值
f1 = draw_pie(sizes,labels)
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
f2 = draw_pie(sizes,labels)
root = "<title>Iris Dataset</title>"
report = u"<h3>1.1 总览</h3><br /> 验收总数:<font color=red><b>100</b></font>; 验收通过数:<font color=red><b>90</b></font>;验收通过率:80%"
root = root + report + f1 + f2
# lxml 库的 etree 解析字符串为 html 代码,并写入文件
html = etree.HTML(root)
tree = etree.ElementTree(html)
buffer = BytesIO()
tree.write(buffer)
tree.write('iris.html')
# 最后使用默认浏览器打开 html 文件
import webbrowser
webbrowser.open('iris.html',new = 1)
linux下使用matplotlib画图解决中文乱码
1、查看matplotlib的配置路径
import matplotlib
print (matplotlib.matplotlib_fname())
得到比如配置路径:
/usr/lib64/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc
2、在window下系统盘下搜索simhei.ttf,或者下载simhei.ttf
将simhei.ttf拷贝到/usr/lib64/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/下
3、删除缓存目录
cd ~/.cache; rm -rf matplotlib
4、代码中指定
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False #解决负号'-'显示为方块的问题