Python对比柱状图
时间: 2025-01-28 09:07:59 浏览: 55
### 使用 Python 绘制对比柱状图
为了创建对比柱状图,通常会利用 `matplotlib` 和 `seaborn` 库的功能。下面展示了一个具体的例子,该例子展示了如何通过这两个库来比较不同类别之间的数值。
#### 导入必要的库并准备数据集
首先需要导入所需的库以及准备好用于绘图的数据:
```python
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame({
'group': ['A', 'B', 'C'],
'value_1': [12, 4, 8],
'value_2': [7, 9, 3]
})
```
这段代码构建了一个简单的 DataFrame 来模拟两组不同的测量值[^1]。
#### 设置图表样式和尺寸
接着设定图表的整体外观风格及其大小以便更好地呈现结果:
```python
sns.set_style("whitegrid") # 设定背景网格线的颜色为白色
plt.figure(figsize=(10, 6)) # 调整图形窗口的宽度与高度比例
```
这部分操作有助于提高最终图像的质量,并使其更易于阅读[^2]。
#### 创建对比柱状图
现在可以调用 `barplot()` 函数分别针对每一列数值绘制条形,并指定颜色区分它们:
```python
p1 = sns.barplot(x="group", y="value_1", data=df, color="skyblue", label='Value 1')
p2 = sns.barplot(x="group", y="value_2", data=df, color="salmon", label='Value 2')
for bar in p1.patches:
p1.annotate(format(bar.get_height(), '.0f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=10, xytext=(0, 8),
textcoords='offset points')
for bar in p2.patches:
p2.annotate(format(bar.get_height(), '.0f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='bottom',
size=10, xytext=(0, 8),
textcoords='offset points')
```
这里不仅实现了两个变量在同一张图上的可视化表示,还添加了标签显示具体数值以增强可读性。
#### 添加标题和其他细节
最后一步是完善整个图表的信息量,比如增加一个描述性的主标题、坐标轴名称等:
```python
plt.title('Comparison of Two Value Sets Across Groups', fontsize=16)
plt.xlabel('Groups', fontsize=14)
plt.ylabel('Values', fontsize=14)
# 显示图例说明各部分含义
plt.legend()
# 展示所作图表
plt.show()
```
上述过程完整地介绍了怎样运用 `matplotlib` 及 `seaborn` 实现一组具有直观对比效果的柱状图[^3]。
阅读全文
相关推荐


















