📅  最后修改于: 2023-12-03 15:37:51.787000             🧑  作者: Mango
Matplotlib 是一个 Python 绘图库。它可与 NumPy 一起使用,提供了一种有效的 Matlab 类似的绘图框架。这里将介绍如何使用 Matplotlib 来绘制多条条形图。
首先,我们需要准备多组数据。这里我们使用 Python 的列表来存储数据:
import numpy as np
# 数据
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5']
使用 Matplotlib 来绘制多条条形图,我们需要指定 x 轴和 y 轴的值。这里我们使用 bar
函数来绘制条形图。还需要注意同一横坐标上的条形图要有一定距离。
import matplotlib.pyplot as plt
x = np.arange(len(labels))
width = 0.35 # 条形图的宽度
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, yerr=men_std,
label='Men')
rects2 = ax.bar(x + width/2, women_means, width, yerr=women_std,
label='Women')
# 添加标签和说明
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# 添加数值标签
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height"""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
# 多条条形图 matplotlib
Matplotlib 是一个 Python 绘图库。它可与 NumPy 一起使用,提供了一种有效的 Matlab 类似的绘图框架。这里将介绍如何使用 Matplotlib 来绘制多条条形图。
## 准备数据
首先,我们需要准备多组数据。这里我们使用 Python 的列表来存储数据:
```python
import numpy as np
# 数据
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
labels = ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5']
使用 Matplotlib 来绘制多条条形图,我们需要指定 x 轴和 y 轴的值。这里我们使用 bar
函数来绘制条形图。还需要注意同一横坐标上的条形图要有一定距离。
import matplotlib.pyplot as plt
x = np.arange(len(labels))
width = 0.35 # 条形图的宽度
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, yerr=men_std,
label='Men')
rects2 = ax.bar(x + width/2, women_means, width, yerr=women_std,
label='Women')
# 添加标签和说明
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
# 添加数值标签
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height"""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()