matplotlib绘多柱状图加表格代码
时间: 2023-06-19 19:10:19 浏览: 75
matplotlib作图添加表格实例代码
下面是一个绘制多柱状图加表格的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
data = np.random.randint(0, 10, (4, 3))
rows, cols = data.shape
# 设置柱状图的参数
bar_width = 0.2
bar_positions = np.arange(cols)
# 绘制柱状图
fig, ax = plt.subplots()
for i in range(rows):
ax.bar(bar_positions + i * bar_width, data[i], bar_width, label=f"Series {i+1}")
# 添加表格
cell_text = []
for i in range(rows):
cell_text.append([f"{val:.2f}" for val in data[i]])
table = ax.table(cellText=cell_text, colLabels=["Column 1", "Column 2", "Column 3"],
rowLabels=[f"Series {i+1}" for i in range(rows)], loc="bottom")
# 设置表格的样式
table.auto_set_font_size(False)
table.set_fontsize(12)
table.scale(1, 1.5)
# 设置图形标题和坐标轴标签
ax.set_title("Multiple Bar Chart with Table")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
# 添加图例
ax.legend()
plt.show()
```
代码的执行结果如下所示:
![multiple_bar_chart_with_table](https://cdn.jsdelivr.net/gh/tsyccnh/image-repo/img/multiple_bar_chart_with_table.png)
阅读全文