添加自定义样式的表格
matplotlib可以绘制各种各样的图表,matplotlib中提供了为图表添加数据表格的函数table(),该函数的语法格式如下所示:
table(cellText=None, cellColours=None, cellLoc='right', colWidths=None,
rowLables=None, rowColours=None, rowLoc='left', colLabels=None,
colColours=None, colLoc='center', loc='bottom', bbox=None,
edges='closed', **kwargs)
该函数常用参数表示的含义如下:
cellText:表示表格单元格中的数据,是一个二维列表。
cellColours :表示单元格的背景颜色。
cellLoc:表示单元格文本的对齐方式,支持'left'、'right'和'center'三种取值,默认值'right'。
colWidths :表示每列的宽度。
rowLabels:表示行标题的文本。
rowColours :表示行标题所在单元格的背景颜色。
rowLoc:表示行标题的对齐方式。
colLabels:表示列标题的文本。
colColours :表示列标题所在单元格的背景颜色。
colLoc:表示列标题的对齐方式。
loc :表示表格与绘图区域的对齐方式。
实例:果酱面包配料比例
配料名称 | 重量(g) |
---|---|
面粉 | 250 |
全麦粉 | 150 |
酵母 | 4 |
苹果酱 | 250 |
鸡蛋 | 50 |
黄油 | 30 |
盐 | 4 |
白糖 | 20 |
用pie()绘制饼图直观了解数据,使用Axes对象的table()方法为图表添加数据表格
步骤一:导入模块
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
步骤二:创建画布并添加绘图区域
# 创建画布
fig = plt.figure()
# 在画布上添加绘图区域
ax = fig.add_subplot(111)
步骤三:绘制饼图
# 绘制饼图
kinds = ['面粉', '全麦粉', '酵母', '苹果酱', '鸡蛋', '黄油', '盐', '白糖']
weight = [250, 150, 4, 250, 50, 30, 4, 20]
ax.pie(weight, autopct='%3.1f%%')
步骤四:添加图例
#添加图例(通过bbox_to_anchor精细调整图例位置)
ax.legend(kinds, loc='right', bbox_to_anchor=[2.1, 0.7],ncol=4)
步骤五: 设置单元格颜色
#单元格背景颜色
colors=['green','green','green','green','green','green','green','green']
步骤六:添加表格
# 添加表格(通过bbox精细调整表格位置和大小)
ax.table(cellText=[weight], cellLoc='center', rowLabels=['重量(g)'], colLabels=kinds,loc='bottom',
bbox=[1.17,0.35,0.8,0.25],colColours=colors, rowColours=['pink'],cellColours=[colors])
最后:展示图表
plt.show()
完整代码如下:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建画布
fig = plt.figure()
# 在画布上添加绘图区域
ax = fig.add_subplot(111)
# 绘制饼图
kinds = ['面粉', '全麦粉', '酵母', '苹果酱', '鸡蛋', '黄油', '盐', '白糖']
weight = [250, 150, 4, 250, 50, 30, 4, 20]
ax.pie(weight, autopct='%3.1f%%')
# 添加图例(通过bbox_to_anchor精细调整图例位置)
ax.legend(kinds, loc='right', bbox_to_anchor=[2.1, 0.7],ncol=4)
#单元格背景颜色
colors=['green','green','green','green','green','green','green','green']
# 添加表格(通过bbox精细调整表格位置和大小)
ax.table(cellText=[weight], cellLoc='center', rowLabels=['重量(g)'], colLabels=kinds,loc='bottom',
bbox=[1.17,0.35,0.8,0.25],colColours=colors, rowColours=['green'],cellColours=[colors])
plt.show()