首先导入库:
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', bbox_to_anchor=[1.1, 1.0])
# 添加表格(通过bbox精细调整表格位置和大小)
plt.table(cellText=[weight], cellLoc='center', rowLabels=['重量(g)'], colLabels=kinds, loc='right')
最后输出:
# matplotlib中文网 https://www.matplotlib.org
# 需求一: 图例用4列展示
# 需求二: 表格填充你喜欢的任意颜色
# 需求三: 调整图例和表格位置,如运行效果图所示(不要求完全一致,但应做到相似度8成以上)。
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%%')
# 添加图例(通过bbox_to_anchor精细调整图例位置)
plt.legend(kinds, loc='upper right', bbox_to_anchor=[1.6, 0.7],ncol=4)
#表格填充颜色
cellColors = [['blue']*8]
rowColors = ['blue']
colColors = ['pink']*8
# 添加表格(通过bbox精细调整表格位置和大小)
plt.table(cellText=[weight], cellLoc='center', rowLabels=['重量(g)'], colLabels=kinds,
rowColours=rowColors, colColours=colColors, cellColours=cellColors,loc='right',)
bbox=[1.0,1,1.2,1.5]
plt.show()
这是效果图: