怎么用Python绘制柱形图

发布时间:2021-08-12 15:32:10 作者:chen
来源:亿速云 阅读:173
# 怎么用Python绘制柱形图

柱形图(Bar Chart)是数据可视化中最基础的图表类型之一,通过不同高度的矩形条展示各类别数据的对比关系。Python凭借丰富的可视化库(如Matplotlib、Seaborn、Plotly等)可以快速生成专业级柱形图。本文将详细讲解5种主流绘制方法,并提供完整代码示例。

## 一、基础工具准备

### 1.1 安装必备库
```bash
pip install matplotlib pandas seaborn plotly

1.2 导入基础模块

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

二、Matplotlib基础柱形图

2.1 单系列柱形图

categories = ['A', 'B', 'C', 'D']
values = [15, 24, 18, 27]

plt.figure(figsize=(8, 6))
bars = plt.bar(categories, values, 
               color='skyblue',
               edgecolor='navy',
               linewidth=2)

# 添加数据标签
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height}',
             ha='center', va='bottom')

plt.title('基础柱形图示例', fontsize=14)
plt.xlabel('类别', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

2.2 多系列并列柱形图

labels = ['Q1', 'Q2', 'Q3', 'Q4']
men_means = [20, 34, 30, 35]
women_means = [25, 32, 34, 20]

x = np.arange(len(labels))
width = 0.35  # 柱宽

fig, ax = plt.subplots(figsize=(10,6))
rects1 = ax.bar(x - width/2, men_means, width, 
                label='男性', color='royalblue')
rects2 = ax.bar(x + width/2, women_means, width, 
                label='女性', color='lightcoral')

ax.set_ylabel('销售额(万元)')
ax.set_title('季度销售数据对比')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

# 自动调整标签位置
fig.tight_layout()
plt.show()

三、Pandas集成绘图

3.1 直接使用DataFrame绘图

df = pd.DataFrame({
    '城市': ['北京', '上海', '广州', '深圳'],
    'GDP': [40300, 43200, 28200, 30600],
    '人口': [2171, 2487, 1868, 1756]
})

ax = df.plot.bar(x='城市', y=['GDP', '人口'],
                figsize=(10,6),
                color=['#1f77b4', '#ff7f0e'],
                rot=0)

ax.set_title('城市经济数据对比', pad=20)
ax.set_ylabel('数值')
plt.grid(axis='y', alpha=0.3)
plt.show()

3.2 堆叠柱形图

product_data = pd.DataFrame({
    'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
    'Product_A': [230, 145, 180, 210],
    'Product_B': [120, 195, 210, 180],
    'Product_C': [90, 110, 130, 150]
})

ax = product_data.plot.bar(x='Quarter',
                         stacked=True,
                         figsize=(10,6),
                         colormap='Paired')

ax.set_ylabel('销售额(万)')
ax.set_title('季度产品销售额堆叠图')
plt.legend(bbox_to_anchor=(1.05, 1))
plt.tight_layout()
plt.show()

四、Seaborn高级可视化

4.1 带误差棒的柱形图

import seaborn as sns

tips = sns.load_dataset("tips")
plt.figure(figsize=(10,6))

ax = sns.barplot(x="day", y="total_bill", 
                data=tips,
                ci=95,  # 95%置信区间
                palette="Blues_d",
                capsize=0.1)

ax.set_title('每日账单金额分布(含置信区间)')
plt.show()

4.2 分组柱形图

plt.figure(figsize=(12,7))
sns.set(style="whitegrid")

ax = sns.barplot(x="day", y="total_bill", 
                hue="sex",
                data=tips,
                palette=["#3498db", "#e74c3c"],
                saturation=0.8)

ax.set_title('不同性别每日消费对比')
ax.legend(title='性别')
plt.show()

五、Plotly交互式图表

5.1 基础交互柱形图

import plotly.express as px

data = px.data.gapminder().query("country == ['China', 'India', 'Japan']")

fig = px.bar(data, x='year', y='pop',
             color='country',
             title='亚洲人口大国人口变化',
             labels={'pop':'人口数量'},
             height=500)

fig.update_layout(hovermode="x unified")
fig.show()

5.2 动画柱形图

df = px.data.gapminder()

fig = px.bar(df, x="continent", y="gdpPercap",
             animation_frame="year",
             color="continent",
             hover_name="country",
             range_y=[0,50000])

fig.update_layout(title='各大洲人均GDP年度变化')
fig.show()

六、高级定制技巧

6.1 渐变色柱形图(Matplotlib)

from matplotlib.cm import ScalarMappable

data = [12, 25, 18, 30, 22]
colors = plt.cm.viridis(np.linspace(0, 1, len(data)))

fig, ax = plt.subplots(figsize=(10,6))
bars = ax.bar(range(len(data)), data, color=colors)

# 添加渐变色条
sm = ScalarMappable(cmap='viridis', 
                   norm=plt.Normalize(min(data), max(data)))
plt.colorbar(sm, ax=ax)

plt.title('渐变色柱形图示例')
plt.show()

6.2 圆角柱形图

from matplotlib.patches import Rectangle

fig, ax = plt.subplots(figsize=(10,6))

for i, val in enumerate([20, 35, 30, 25]):
    rect = Rectangle((i-0.4, 0), 0.8, val,
                    color='#3498db',
                    linewidth=2,
                    edgecolor='#2980b9',
                    joinstyle='round',  # 关键参数
                    capstyle='round')
    ax.add_patch(rect)
    ax.text(i, val+1, str(val), ha='center')

ax.set_xlim(-0.5, 4)
ax.set_ylim(0, 40)
ax.set_xticks([0,1,2,3])
ax.set_xticklabels(['A','B','C','D'])
plt.title('圆角柱形图')
plt.show()

七、常见问题解决方案

7.1 中文显示问题

plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows
plt.rcParams['axes.unicode_minus'] = False

7.2 柱形图标签重叠

plt.xticks(rotation=45, ha='right')  # 旋转45度

7.3 调整柱形间距

plt.bar(x, height, width=0.6)  # 默认0.8

八、应用场景示例

8.1 销售数据可视化

months = ['Jan', 'Feb', 'Mar', 'Apr']
sales = [120, 145, 130, 160]
target = [100, 120, 150, 140]

fig, ax = plt.subplots(figsize=(10,6))
ax.bar(months, sales, label='实际销售')
ax.plot(months, target, 'ro--', label='销售目标')

ax.set_title('月度销售达成情况')
ax.legend()
plt.show()

8.2 问卷调查结果展示

questions = ['问题1', '问题2', '问题3']
agree = [75, 60, 45]
disagree = [25, 40, 55]

x = np.arange(len(questions))
plt.figure(figsize=(10,6))

plt.barh(x + 0.2, agree, 0.4, label='同意')
plt.barh(x - 0.2, disagree, 0.4, label='不同意')

plt.yticks(x, questions)
plt.legend()
plt.title('问卷调查结果')
plt.show()

九、性能优化建议

  1. 大数据集处理:当数据点超过1000时,考虑使用plt.hist()或采样显示
  2. 矢量图输出:保存为PDF/SVG格式获得更高清效果
plt.savefig('output.pdf', format='pdf', dpi=300)
  1. 动态更新:对于实时数据,使用plt.clf()清除当前图形而非创建新figure

十、完整案例演示

10.1 电商平台销售分析

# 准备数据
np.random.seed(42)
categories = ['电子产品', '服装', '食品', '家居']
q1_sales = np.random.randint(50, 200, size=4)
q2_sales = np.random.randint(60, 250, size=4)

# 创建画布
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6))

# 子图1:季度对比
width = 0.35
x = np.arange(len(categories))
ax1.bar(x - width/2, q1_sales, width, label='第一季度')
ax1.bar(x + width/2, q2_sales, width, label='第二季度')
ax1.set_title('分季度销售对比')
ax1.set_xticks(x)
ax1.set_xticklabels(categories)
ax1.legend()

# 子图2:增长率
growth_rate = (q2_sales - q1_sales)/q1_sales * 100
colors = ['green' if x >=0 else 'red' for x in growth_rate]
ax2.bar(categories, growth_rate, color=colors)
ax2.axhline(0, color='black', linewidth=0.8)
ax2.set_title('季度增长率(%)')

plt.tight_layout()
plt.show()

通过以上示例,我们可以看到Python绘制柱形图既简单又强大。不同库有各自的特点: - Matplotlib:最基础灵活,适合需要精细控制的场景 - Pandas:与DataFrame完美集成,快速可视化 - Seaborn:统计特性丰富,美观的默认样式 - Plotly:交互式可视化,适合网页展示

建议初学者从Matplotlib开始掌握基本原理,再根据实际需求选择更高级的库。 “`

推荐阅读:
  1. d3怎么绘制基本的柱形图
  2. 怎么用Python绘制几个动画

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么用Python将word文件转换成html

下一篇:怎么用python读取excel

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》