Matplotlib 条形图
最后修改于 2025 年 2 月 25 日
Matplotlib 是一个强大的 Python 库,用于创建静态、动画和交互式可视化。 条形图是用于比较分类数据的最常见图表类型之一。 本教程介绍如何使用 Matplotlib 创建各种类型的条形图。
条形图非常适合可视化离散数据,例如跨类别的计数或百分比。 Matplotlib 提供了一个灵活且易于使用的界面,用于创建具有自定义的条形图。
基本条形图
此示例演示如何创建基本条形图。
basic_bar_chart.py
import matplotlib.pyplot as plt
# Data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Create a bar chart
plt.bar(categories, values)
# Add labels and title
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Basic Bar Chart")
# Display the chart
plt.show()
plt.bar() 函数用于创建条形图。 plt.show() 函数显示图表。
水平条形图
此示例演示如何创建水平条形图。
horizontal_bar_chart.py
import matplotlib.pyplot as plt
# Data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Create a horizontal bar chart
plt.barh(categories, values)
# Add labels and title
plt.xlabel("Values")
plt.ylabel("Categories")
plt.title("Horizontal Bar Chart")
# Display the chart
plt.show()
plt.barh() 函数用于创建水平条形图。
分组条形图
此示例演示如何创建分组条形图。
grouped_bar_chart.py
import matplotlib.pyplot as plt
import numpy as np
# Data
categories = ['A', 'B', 'C', 'D']
values1 = [10, 20, 15, 25]
values2 = [15, 25, 20, 30]
# Set the width of the bars
bar_width = 0.35
# Create positions for the bars
x = np.arange(len(categories))
# Create grouped bars
plt.bar(x - bar_width/2, values1, width=bar_width, label="Group 1")
plt.bar(x + bar_width/2, values2, width=bar_width, label="Group 2")
# Add labels, title, and legend
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Grouped Bar Chart")
plt.xticks(x, categories)
plt.legend()
# Display the chart
plt.show()
np.arange() 函数用于创建条形的位置。 width 参数控制条形的宽度。
堆叠条形图
此示例演示如何创建堆叠条形图。
stacked_bar_chart.py
import matplotlib.pyplot as plt
# Data
categories = ['A', 'B', 'C', 'D']
values1 = [10, 20, 15, 25]
values2 = [15, 25, 20, 30]
# Create stacked bars
plt.bar(categories, values1, label="Group 1")
plt.bar(categories, values2, bottom=values1, label="Group 2")
# Add labels, title, and legend
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Stacked Bar Chart")
plt.legend()
# Display the chart
plt.show()
bottom 参数用于将第二组条形堆叠在第一组条形之上。
自定义条形图
此示例演示如何使用颜色、边框颜色和图案自定义条形图。
custom_bar_chart.py
import matplotlib.pyplot as plt
# Data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Create a bar chart with custom styles
plt.bar(categories, values, color="skyblue", edgecolor="black", hatch="/")
# Add labels and title
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Custom Bar Chart")
# Display the chart
plt.show()
color、edgecolor 和 hatch 参数用于自定义条形的外观。
条形图的最佳实践
- 清晰标注轴:始终为 X 轴和 Y 轴添加标签,以使图表易于理解。
- 使用图例: 在绘制多个组时添加图例以区分它们。
- 选择合适的颜色: 使用对比鲜明的颜色来区分多个组,以提高可读性。
- 限制类别: 避免使用过多的类别来使图表变得混乱。
来源
在本文中,我们探讨了使用 Matplotlib 的各种类型的条形图,包括基本条形图、水平条形图、分组条形图、堆叠条形图和自定义条形图。
作者
列出 所有 Python 教程。