Matplotlib - 条形图
Matplotlib - 条形图 (Bar Plot / Bar Chart)
Section titled “Matplotlib - 条形图 (Bar Plot / Bar Chart)”条形图 (Bar Chart 或 Bar Graph) 是一种基本的可视化方式,用于用矩形条表示分类数据 (categorical data)。每个条的长度或高度与其代表的值成比例。条形图非常适合比较不同类别之间的离散值 (discrete values)。
Matplotlib 提供了 ax.bar() 方法用于创建垂直条形图,以及 ax.barh() 用于创建水平条形图。
简单的垂直条形图 (ax.bar)
Section titled “简单的垂直条形图 (ax.bar)”ax.bar(x, height, width=0.8, bottom=None, align='center', **kwargs)x: 表示条形图的 x 坐标(位置)或类别标签的标量或字符串序列。height: 表示条形图高度的标量或标量序列。width: 标量或类似数组的类型(默认值 0.8)。条形图的宽度。bottom: 标量或类似数组的类型(默认值 None)。条形图底部的 y 坐标(用于堆叠图)。align: {‘center’, ‘edge’}。条形图相对于x坐标的对齐方式。color,edgecolor,linewidth,label,alpha: 标准绘图关键字参数。
示例:不同课程的学生人数。
import matplotlib.pyplot as plt
# 数据courses = ['C', 'C++', 'Java', 'Python', 'PHP']students = [23, 17, 35, 29, 12]
fig, ax = plt.subplots(figsize=(7, 5))
# 创建条形图bars = ax.bar(courses, students, color='skyblue', edgecolor='black')
# 添加标签和标题ax.set_xlabel('Programming Language')ax.set_ylabel('Number of Students Enrolled')ax.set_title('Course Enrollment')ax.grid(axis='y', linestyle='--', alpha=0.7)
# 可选:在条形图顶部添加数据标签ax.bar_label(bars, padding=3)
plt.show()分组条形图 (Grouped Bar Chart)
Section titled “分组条形图 (Grouped Bar Chart)”要在同一类别下比较多个系列 (series),你可以创建分组条形图。这需要为每个系列计算条形图的偏移 x 坐标。
import matplotlib.pyplot as pltimport numpy as np
# 数据:3 种产品在 4 个季度的销售额labels = ['Q1', 'Q2', 'Q3', 'Q4']product_a_sales = [30, 25, 50, 20]product_b_sales = [40, 23, 51, 17]product_c_sales = [35, 22, 45, 19]
# 计算条形图位置x = np.arange(len(labels)) # 标签位置 [0, 1, 2, 3]width = 0.25 # 每个条形图的宽度
fig, ax = plt.subplots(figsize=(10, 6))
rects1 = ax.bar(x - width, product_a_sales, width, label='Product A', color='cornflowerblue')rects2 = ax.bar(x, product_b_sales, width, label='Product B', color='lightcoral')rects3 = ax.bar(x + width, product_c_sales, width, label='Product C', color='lightgreen')
# 添加标签、标题和图例ax.set_ylabel('Sales Figures')ax.set_title('Quarterly Sales by Product')ax.set_xticks(x) # 将 x 轴刻度位置设置在分组的中心ax.set_xticklabels(labels)ax.legend()ax.grid(axis='y', linestyle='--', alpha=0.7)
# 添加数据标签ax.bar_label(rects1, padding=3)ax.bar_label(rects2, padding=3)ax.bar_label(rects3, padding=3)
fig.tight_layout()plt.show()堆叠条形图 (Stacked Bar Chart)
Section titled “堆叠条形图 (Stacked Bar Chart)”堆叠条形图显示不同系列在每个类别中对总数的贡献。你在后续的 ax.bar() 调用中使用 bottom 参数,将条形图堆叠在彼此之上。
import matplotlib.pyplot as pltimport numpy as np
# 数据:两组在 5 个类别中的得分贡献labels = ['G1', 'G2', 'G3', 'G4', 'G5']men_means = np.array([20, 35, 30, 35, 27])women_means = np.array([25, 32, 34, 20, 25])width = 0.5 # 条形图的宽度
fig, ax = plt.subplots(figsize=(8, 6))
# 绘制男性的得分(底部层)bar1 = ax.bar(labels, men_means, width, label='Men', color='dodgerblue')
# 在男性的得分顶部绘制女性的得分bar2 = ax.bar(labels, women_means, width, bottom=men_means, label='Women', color='hotpink')
ax.set_ylabel('Scores')ax.set_title('Scores by Group and Gender (Stacked)')ax.legend()ax.grid(axis='y', linestyle='--', alpha=0.7)
# 添加数据标签(可选,可能会显得拥挤)# ax.bar_label(bar1, label_type='center')# ax.bar_label(bar2, label_type='center')# ax.bar_label(bar2) # 堆叠顶部的标签
plt.show()水平条形图 (ax.barh)
Section titled “水平条形图 (ax.barh)”ax.barh(y, width, height=0.8, left=None, ...) 的工作方式类似于 ax.bar,但创建的是水平条形图。当你的类别标签较长时,通常更适合使用这种方式。