📅  最后修改于: 2023-12-03 15:07:44.218000             🧑  作者: Mango
Matplotlib是一个非常方便的Python数据可视化库,可用于创建各种类型的图形。在本文中,我们将学习如何在Matplotlib中创建分组条形图。
为了创建图形,我们需要导入Matplotlib库并使用它的pyplot模块。我们还将使用NumPy模块来生成一些模拟数据。
import matplotlib.pyplot as plt
import numpy as np
我们需要准备一些模拟数据以绘制分组条形图。以下是一个示例数据集:
labels = ['Group 1', 'Group 2']
men_means = [20, 35]
women_means = [25, 32]
现在,我们可以创建一个空白的Matplotlib图形,设置参数并添加标题和标签。
fig, ax = plt.subplots()
index = np.arange(len(labels))
bar_width = 0.35
opacity = 0.8
rects1 = ax.bar(index, men_means, bar_width,
alpha=opacity, color='b',
label='Men')
rects2 = ax.bar(index + bar_width, women_means, bar_width,
alpha=opacity, color='g',
label='Women')
ax.set_xlabel('Group')
ax.set_ylabel('Scores')
ax.set_title('Scores by Group and Gender')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(labels)
ax.legend()
最后,我们使用plt.show()函数显示图形。
plt.show()
import matplotlib.pyplot as plt
import numpy as np
labels = ['Group 1', 'Group 2']
men_means = [20, 35]
women_means = [25, 32]
fig, ax = plt.subplots()
index = np.arange(len(labels))
bar_width = 0.35
opacity = 0.8
rects1 = ax.bar(index, men_means, bar_width,
alpha=opacity, color='b',
label='Men')
rects2 = ax.bar(index + bar_width, women_means, bar_width,
alpha=opacity, color='g',
label='Women')
ax.set_xlabel('Group')
ax.set_ylabel('Scores')
ax.set_title('Scores by Group and Gender')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(labels)
ax.legend()
plt.show()
以下是输出的分组条形图:
如您所见,使用Matplotlib创建分组条形图非常容易!