案例:果酱面包配料比例
先弄一行代码,如下图所示:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
kinds = ['面粉', '全麦粉', '酵母', '苹果酱', '鸡蛋', '黄油', '盐', '白糖']
weight = [250, 150, 4, 250, 50, 30, 4, 20]
plt.pie(weight, autopct = '%3.1f%%')
plt.legend(kinds, loc = 'upper right', ncol = 4, bbox_to_anchor = [2.1, 0.7])
plt.table(cellText = [weight], cellColours = ['c' * 8], colWidths = [0.15] * 8, colColours = 'c' * 8,
rowColours = 'c', cellLoc = 'center', rowLabels = ['重量(g)'], colLabels = kinds, loc = 'right', bbox = [1.2, 0.2, 1, 0.24])
plt.show()
运行结果图如下所示:
解释一下,首先,我们要先导入pyplot模块,并将模块命名为plt
import matplotlib.pyplot as plt
下一步,将标题修改中文格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
下一步,开始绘制饼图,同时插入文本数据和数字数据以及设置数字数据的百分点
weight = [250, 150, 4, 250, 50, 30, 4, 20]
plt.pie(weight, autopct = '%3.1f%%')
下一步,添加图例,在这里,我们要设置图例的位置,插入文本数据。
plt.legend(kinds, loc = 'upper right', ncol = 4, bbox_to_anchor = [2.1, 0.7])
下一步,添加表格,插入单元格数据,设置单元格的背景颜色,列标题所在单元格的背景颜色,行标题所在单元格的背景颜色,还有表格位置,每列的宽度。
plt.table(cellText = [weight], cellColours = ['c' * 8], colWidths = [0.15] * 8, colColours = 'c' * 8,
rowColours = 'c', cellLoc = 'center', rowLabels = ['重量(g)'], colLabels = kinds, loc = 'right', bbox = [1.2, 0.2, 1, 0.24])
最后,展示图像,也就是上面那个运行结果图
plt.show()