python中matplotlib绘图封装类之折线图条状图圆饼图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中matplotlib绘图封装类之折线图条状图圆饼图相关的知识,希望对你有一定的参考价值。
DrawHelper.py封装类源码:
1 import matplotlib 2 import matplotlib.pyplot as plt 3 import numpy as np 4 5 class DrawHelper: 6 def __init__(self): 7 # 指定默认字体 下面三条代码用来解决绘图中出现的乱码 8 matplotlib.rcParams[‘font.sans-serif‘] = [‘SimHei‘] 9 matplotlib.rcParams[‘font.family‘] = ‘sans-serif‘ 10 # 解决负号‘-‘显示为方块的问题 11 matplotlib.rcParams[‘axes.unicode_minus‘] = False 12 13 # 绘制饼状图清除type值为零,同时设置颜色(相同的类型相同的颜色) 14 def clear_zeroData(self, keys, values): 15 colors = [‘yellow‘, ‘green‘, ‘red‘, ‘blue‘, ‘black‘, ‘purple‘, ‘pink‘, ‘brown‘, ‘grey‘, ‘yellow‘, ‘green‘, ‘red‘, ‘blue‘, ‘black‘, ‘purple‘, ‘pink‘, ‘brown‘, ‘grey‘, ‘yellow‘, ‘green‘, ‘red‘, ‘blue‘, ‘black‘, ‘purple‘, ‘pink‘, ‘brown‘, ‘grey‘] 16 keys_list = [] 17 values_list = [] 18 colors_list = [] 19 for i in range(0, len(keys)): 20 if values[i] != 0: 21 keys_list.append(keys[i]) 22 values_list.append(values[i]) 23 colors_list.append(colors[i]) 24 return (keys_list,values_list,colors_list) 25 26 # 绘制折线图 27 def get_plot(self, key_list, value_list, actor): 28 index = np.arange(len(key_list)) 29 # 设置画板大小 30 plt.figure(figsize=(9,9)) 31 # 设置条状图标题 32 plt.title(actor+‘电影类型分布折线图‘) 33 plt.xticks(index, key_list) 34 plt.grid(True) 35 plt.plot(index,value_list) 36 # 保存成图片 37 plt.savefig(‘images/plot/‘ + actor + ‘.png‘) 38 plt.close() 39 40 # 绘制条状图 41 def get_bar(self, key_list, value_list, actor): 42 index = np.arange(len(key_list)) 43 # 设置画板大小 44 plt.figure(figsize=(9,9)) 45 # 设置条状图标题 46 plt.title(actor + ‘电影类型分布直方图‘) 47 plt.bar(index, value_list, 0.5) 48 plt.xticks(index, key_list) 49 plt.grid(True) 50 plt.savefig(‘images/bar/‘ + actor + ‘.png‘) 51 # 关闭图 52 plt.close() 53 54 # 绘制饼状图 55 def get_pie(self, key_list, value_list, actor): 56 # 调用绘制饼状图清除type值为零,同时设置颜色函数 57 types_no_zero = self.clear_zeroData(key_list,value_list) 58 keys = types_no_zero[0] 59 values = types_no_zero[1] 60 colors = types_no_zero[2] 61 # 设置标题 62 plt.title(actor + ‘电影类型分布饼状图‘) 63 plt.pie(values, labels=keys, colors=colors,shadow=True, autopct=‘%1.1f%%‘) 64 plt.axis(‘equal‘) 65 plt.savefig(‘images/pie/‘ + actor + ‘.png‘) 66 # 关闭图 67 plt.close()
test.py测试:
1 from DrawHelper import DrawHelper 2 3 types = ([‘剧情‘, ‘喜剧‘, ‘爱情‘, ‘动作‘, ‘犯罪‘, ‘武侠‘, ‘悬疑‘, ‘古装‘, ‘科幻‘, ‘惊悚‘, ‘奇幻‘, ‘恐怖‘, ‘鬼怪‘, ‘冒险‘, ‘家庭‘, ‘运动‘, ‘西部‘, ‘传记‘, ‘歌舞‘, ‘历史‘, ‘同性‘], [11, 2, 3, 8, 10, 0, 2, 0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]) 4 keys = types[0] 5 values = types[1] 6 actor = ‘刘德华‘ 7 DrawHelper().get_bar(keys,values,actor) 8 DrawHelper().get_pie(keys,values,actor) 9 DrawHelper().get_plot(keys,values,actor) 10 print("OK")
截图:
以上是关于python中matplotlib绘图封装类之折线图条状图圆饼图的主要内容,如果未能解决你的问题,请参考以下文章
python数据分析-matplotlib折线图知识总结01