SUNNY-yl

导航

 

前言

测试执行结果发送报告时,分析图标比文案描述表达效果更好,来看下效果吧

 

 

 

代码实现

 1 import matplotlib.pyplot as plt
 2 
 3 def pie(x,labels,title):
 4     plt.figure(figsize=(7,5))
 5     plt.rcParams['font.sans-serif'] = ['SimHei']
 6     plt.pie(x,labels=labels,radius=0.9,autopct='%0.1f%%')
 7     plt.title(title)
 8     plt.show()
 9 if __name__ == '__main__':
10     labels = ['UI自动化:10条', '接口自动化:2条', 'codeReview:3条', '静态扫描:1条', '单元测试:4条']
11     x = [10, 2, 3, 1, 4]
12     title = '不合格类型占比分布图'
13     pie(x,labels,title)

以上操作可以在控制台输出饼图,但是需要展示在前端或者邮件中,就需要保存成文件格式,代码如下

 1 import matplotlib.pyplot as plt
 2 import time
 3 import base64
 4 
 5 def pie(x,labels,title):
 6     plt.figure(figsize=(7,5))
 7     plt.rcParams['font.sans-serif'] = ['SimHei']
 8     plt.pie(x,labels=labels,radius=0.9,autopct='%0.1f%%')
 9     plt.title(title)
10     #控制台展示
11     # plt.show()
12     #保存为文件
13     image_path = "D:\\develop\\vega\\source\\pie.jpeg"
14     plt.savefig(image_path)
15     time.sleep(3)
16 
17     #jpeg转为bytes
18     with open(image_path,'rb') as f:
19         s = f.read()
20         res = base64.b64encode(s)
21         return str(res.decode())
22 
23 
24 if __name__ == '__main__':
25     labels = ['UI自动化:10条', '接口自动化:2条', 'codeReview:3条', '静态扫描:1条', '单元测试:4条']
26     x = [10, 2, 3, 1, 4]
27     title = '不合格类型占比分布图'
28     image_bytes = pie(x,labels,title)
29     print(image_bytes)

 

在django templates中展示

1 #report.html
2 ...
3 <img src="data:image/jpeg;base64,{{ image_bytes }}" height="100" width="100"  />
4 ...

 

饼状图绘图原理

Python中绘制饼状图需用matplotlib.pyplot中的pie函数,该函数的基本语法为:

1 pie(x, [explode], [labels], [colors], [autopct], [pctdistance],  [labeldistance], [startangle], [radius], [textprops], **kwargs)

参数说明:
  
x:数组,绘制饼状图的数据。
  
[explode]:默认值为None的可选参数。若非None,则是和x相同长度的数组,用来指定每部分的离心偏移量。
  
[labels]:列表,指定每个饼块的名称,默认值None,为可选参数。
  
[colors]:特定字符或数组,指定饼图的颜色,默认值None,为可选参数。
  
[autopct]:特定字符,指定饼图中数据标签的显示方式,默认值None,为可选参数。
  
[pctdistance]:浮点数,指定显示比例距离圆心的距离。默认值0.6,为可选参数。
  
[labeldistance]:浮点数,指定每个扇形对应标签与圆心的距离,默认值1.1,为可选参数。
  
[startangle]:浮点数,指定从x轴逆时针旋转饼图的开始角度,默认值None,为可选参数。
  
[radius]:浮点数,指定饼图的半径,默认值1,为可选参数。
  
[textprops]:字典,设置文本对象的字典参数,默认值None,为可选参数。
  
**kwargs:不定长关键字参数,用字典形式设置条形图的其它参数。

参考文档:https://blog.csdn.net/qq_32532663/article/details/113631551

 

posted on 2022-08-02 20:49  The依依  阅读(1345)  评论(0编辑  收藏  举报