### 如何使用 Matplotlib 库绘制柱状图
以下是基于提供的引用内容以及专业知识所整理的内容,展示如何利用 `Matplotlib` 绘制柱状图。
#### 基础柱状图
基础柱状图是最简单的形式之一。可以通过 `plt.bar()` 函数实现。以下是一个基本的例子:
```python
import matplotlib.pyplot as plt
# 数据准备
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]
# 创建柱状图
plt.bar(categories, values, color=['blue', 'green', 'red', 'purple'])
# 设置标题和坐标轴标签
plt.title('Basic Bar Chart Example')
plt.xlabel('Categories')
plt.ylabel('Values')
# 显示图像
plt.show()
```
此代码片段展示了如何通过传递类别列表 (`categories`) 和对应的数值列表 (`values`) 来生成一个基础的柱状图[^3]。
---
#### 堆叠柱状图
当需要在同一分类上叠加多组数据时,可以使用堆叠柱状图。这通常用于比较同一类别下的子项差异。
```python
import numpy as np
import matplotlib.pyplot as plt
N = 4
menMeans = (20, 35, 30, 35)
womenMeans = (25, 32, 34, 20)
ind = np.arange(N) # x 轴的位置
width = 0.35 # 柱体宽度
p1 = plt.bar(ind, menMeans, width, label='Men')
p2 = plt.bar(ind, womenMeans, width, bottom=menMeans, label='Women')
plt.ylabel('Scores')
plt.title('Stacked Bar Chart Scores by Group and Gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4'))
plt.yticks(np.arange(0, 81, 10))
plt.legend()
plt.show()
```
上述代码实现了两组数据(男性和女性得分)在一个图表中的堆叠显示[^4]。
---
#### 左右分布柱状图
如果想让两个对比的数据分别分布在中心两侧,则可调整条形的方向来完成这一目标。
```python
import matplotlib.pyplot as plt
import numpy as np
labels = ['Group A', 'Group B', 'Group C']
left_values = [10, 15, 30]
right_values = [-25, -32, -34]
x = np.arange(len(labels)) # 类别的位置
fig, ax = plt.subplots()
bars_left = ax.bar(x - 0.2, left_values, 0.4, label='Left Data', align='center')
bars_right = ax.bar(x + 0.2, right_values, 0.4, label='Right Data', align='center')
ax.axhline(0, color='black', linewidth=0.8) # 添加水平基线
ax.set_ylabel('Values')
ax.set_title('Symmetric Bar Chart with Positive/Negative Values')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
plt.show()
```
这段代码演示了如何将正负值分列于零点两侧形成对称布局。
---
#### 带误差线的柱状图
为了表示每根柱的高度可能存在的不确定性范围,可以在柱顶加上误差棒。
```python
import matplotlib.pyplot as plt
import numpy as np
N = 5
means = (20, 35, 30, 35, 27)
std_devs = (2, 3, 4, 1, 2)
ind = np.arange(N)
width = 0.6
fig, ax = plt.subplots()
rects = ax.bar(ind, means, width, yerr=std_devs, capsize=5, color='SkyBlue', ecolor='Black')
ax.set_ylabel('Scores')
ax.set_title('Bar Chart with Error Bars')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
def autolabel(rects):
"""Attach a text label above each bar."""
for rect in rects:
height = rect.get_height()
ax.annotate(f'{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(rects)
plt.show()
```
这里介绍了带有标准差作为误差指示器的方法[^1]。
---
#### 结合直方图与折线图
有时我们需要在同一个图表里既看到频率分布又观察趋势走向,这时可以用到组合型绘图技术。
```python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = np.random.randn(1000)
fig, ax = plt.subplots()
n, bins, patches = ax.hist(data, bins=50, density=True, alpha=0.75, edgecolor='w')
# 计算并添加拟合曲线
mu, sigma = data.mean(), data.std()
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
ax.plot(bins, y, '--r', linewidth=2)
ax.set_xlabel('Value')
ax.set_ylabel('Probability Density')
ax.set_title(r'Histogram of IQ: $\mu={:.2f}$, $\sigma={:.2f}$'.format(mu, sigma))
plt.grid(True)
plt.show()
```
这个例子说明了怎样把直方统计结果同理论概率密度函数结合起来呈现出来[^2]。
---