python中matplotlib绘图封装类之折线图、条状图、圆饼图

时间:2022-06-25 11:36:39

DrawHelper.py封装类源码:

 import matplotlib
import matplotlib.pyplot as plt
import numpy as np class DrawHelper:
def __init__(self):
# 指定默认字体 下面三条代码用来解决绘图中出现的乱码
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family'] = 'sans-serif'
# 解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus'] = False # 绘制饼状图清除type值为零,同时设置颜色(相同的类型相同的颜色)
def clear_zeroData(self, keys, values):
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']
keys_list = []
values_list = []
colors_list = []
for i in range(0, len(keys)):
if values[i] != 0:
keys_list.append(keys[i])
values_list.append(values[i])
colors_list.append(colors[i])
return (keys_list,values_list,colors_list) # 绘制折线图
def get_plot(self, key_list, value_list, actor):
index = np.arange(len(key_list))
# 设置画板大小
plt.figure(figsize=(9,9))
# 设置条状图标题
plt.title(actor+'电影类型分布折线图')
plt.xticks(index, key_list)
plt.grid(True)
plt.plot(index,value_list)
# 保存成图片
plt.savefig('images/plot/' + actor + '.png')
plt.close() # 绘制条状图
def get_bar(self, key_list, value_list, actor):
index = np.arange(len(key_list))
# 设置画板大小
plt.figure(figsize=(9,9))
# 设置条状图标题
plt.title(actor + '电影类型分布直方图')
plt.bar(index, value_list, 0.5)
plt.xticks(index, key_list)
plt.grid(True)
plt.savefig('images/bar/' + actor + '.png')
# 关闭图
plt.close() # 绘制饼状图
def get_pie(self, key_list, value_list, actor):
# 调用绘制饼状图清除type值为零,同时设置颜色函数
types_no_zero = self.clear_zeroData(key_list,value_list)
keys = types_no_zero[0]
values = types_no_zero[1]
colors = types_no_zero[2]
# 设置标题
plt.title(actor + '电影类型分布饼状图')
plt.pie(values, labels=keys, colors=colors,shadow=True, autopct='%1.1f%%')
plt.axis('equal')
plt.savefig('images/pie/' + actor + '.png')
# 关闭图
plt.close()

test.py测试:

 from DrawHelper import DrawHelper

 types = (['剧情', '喜剧', '爱情', '动作', '犯罪', '武侠', '悬疑', '古装', '科幻', '惊悚', '奇幻', '恐怖', '鬼怪', '冒险', '家庭', '运动', '西部', '传记', '歌舞', '历史', '同性'], [11, 2, 3, 8, 10, 0, 2, 0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0])
keys = types[0]
values = types[1]
actor = '刘德华'
DrawHelper().get_bar(keys,values,actor)
DrawHelper().get_pie(keys,values,actor)
DrawHelper().get_plot(keys,values,actor)
print("OK")

截图:

python中matplotlib绘图封装类之折线图、条状图、圆饼图

python中matplotlib绘图封装类之折线图、条状图、圆饼图

python中matplotlib绘图封装类之折线图、条状图、圆饼图