当前位置: 代码网 > it编程>前端脚本>Python > Python使用Matplotlib绘制专业柱状图的完整指南

Python使用Matplotlib绘制专业柱状图的完整指南

2025年07月25日 Python 我要评论
1. 基础柱状图绘制import matplotlib.pyplot as pltimport numpy as np # 数据准备categories = ['苹果', '香蕉', '橙子', '葡

1. 基础柱状图绘制

import matplotlib.pyplot as plt
import numpy as np
 
# 数据准备
categories = ['苹果', '香蕉', '橙子', '葡萄', '芒果']
sales_volume = [85, 67, 92, 45, 71]
 
# 创建图表
plt.figure(figsize=(10, 6))  # 设置画布大小
plt.bar(categories, sales_volume, color='skyblue', edgecolor='black')
 
# 添加标签和标题
plt.title('水果销售情况', fontsize=14, fontweight='bold')
plt.xlabel('水果种类', fontsize=12)
plt.ylabel('销售量(千克)', fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)  # 添加横向网格线
 
# 显示图表
plt.tight_layout()
plt.show()

2. 自定义样式进阶

# 使用seaborn样式
plt.style.use('seaborn-v0_8-darkgrid')
 
# 数据准备
months = ['1月', '2月', '3月', '4月', '5月']
revenue = [125, 142, 98, 167, 210]
cost = [75, 82, 65, 92, 110]
 
# 创建子图
fig, ax = plt.subplots(figsize=(12, 7))
 
# 绘制柱状图(设置宽度和位置)
bar_width = 0.35
x_indexes = np.arange(len(months))
 
ax.bar(x_indexes - bar_width/2, revenue, width=bar_width, 
        label='收入', color='#2ecc71', edgecolor='black')
ax.bar(x_indexes + bar_width/2, cost, width=bar_width, 
        label='成本', color='#e74c3c', edgecolor='black')
 
# 添加数据标签
for i, v in enumerate(revenue):
    ax.text(i - bar_width/2, v + 5, str(v), ha='center', fontsize=10)
for i, v in enumerate(cost):
    ax.text(i + bar_width/2, v + 5, str(v), ha='center', fontsize=10)
 
# 设置图表元素
ax.set_title('月度收入与成本对比', fontsize=16, pad=20)
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('金额(万元)', fontsize=12)
ax.set_xticks(x_indexes)
ax.set_xticklabels(months)
ax.legend(frameon=true, shadow=true)
 
# 添加横向参考线
ax.axhline(y=150, color='gray', linestyle='--', alpha=0.5)
 
# 设置坐标轴范围
ax.set_ylim(0, 250)
 
# 添加脚注
plt.figtext(0.5, 0.01, '数据来源: 公司财务报告2023', 
            ha='center', fontsize=9, color='gray')
 
plt.tight_layout()
plt.savefig('business_analysis.png', dpi=300)  # 保存高清图片
plt.show()

3. 水平柱状图

# 数据准备
countries = ['美国', '中国', '日本', '德国', '英国']
gdp_growth = [2.3, 5.2, 1.1, 1.8, -0.3]
 
# 创建图表
plt.figure(figsize=(10, 6))
 
# 水平柱状图(负值用不同颜色)
colors = ['#3498db' if x >= 0 else '#e74c3c' for x in gdp_growth]
plt.barh(countries, gdp_growth, color=colors, edgecolor='black')
 
# 添加数据标签
for i, v in enumerate(gdp_growth):
    plt.text(v, i, f'{v}%', 
             va='center', 
             color='black' if abs(v) < 2 else 'white',
             fontweight='bold')
 
# 设置图表元素
plt.title('2023年gdp增长率对比', fontsize=14)
plt.xlabel('增长率(%)')
plt.xlim(-1, 6)
plt.grid(axis='x', alpha=0.5)
 
plt.tight_layout()
plt.show()

4. 堆叠柱状图

# 数据准备
quarters = ['第一季度', '第二季度', '第三季度', '第四季度']
online_sales = [120, 145, 180, 210]
offline_sales = [80, 95, 110, 130]
 
# 创建图表
plt.figure(figsize=(10, 6))
 
# 绘制堆叠柱状图
plt.bar(quarters, online_sales, label='线上销售', color='#9b59b6')
plt.bar(quarters, offline_sales, bottom=online_sales, 
        label='线下销售', color='#3498db')
 
# 添加总销售额标签
total_sales = [online_sales[i] + offline_sales[i] for i in range(len(quarters))]
for i, total in enumerate(total_sales):
    plt.text(i, total + 10, f'总销售额: {total}', 
             ha='center', fontsize=9)
 
# 设置图表元素
plt.title('线上线下销售渠道对比', fontsize=14)
plt.ylabel('销售额(万元)')
plt.legend(loc='upper left')
plt.ylim(0, 400)
 
plt.tight_layout()
plt.show()

5. 专业技巧与最佳实践

配色方案

  • 使用渐变色表示数值大小
  • 重要数据使用突出颜色
  • 保持整体配色协调(可使用coolwarm、viridis等内置色彩映射)

布局优化

plt.figure(figsize=(12, 7), dpi=100)  # 高清输出
plt.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.15)  # 自定义边距

 高级标注

# 添加显著性标记
plt.annotate('创纪录销售', xy=(3, 340), xytext=(3.5, 320),
             arrowprops=dict(arrowstyle='->', color='red'),
             fontsize=10, color='red')

3d柱状图

from mpl_toolkits.mplot3d import axes3d
 
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
 
# 生成3d柱状图数据
xpos = [1, 2, 3, 4]
ypos = [1, 2, 3]
zpos = np.zeros(4)
dx = np.ones(4) * 0.5
dy = np.ones(4) * 0.5
dz = [10, 15, 12, 8]
 
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#1abc9c', shade=true)
ax.set_title('3d销售数据展示', fontsize=14)
ax.set_xlabel('区域')
ax.set_ylabel('季度')
ax.set_zlabel('销售额')

6. 常见问题解决

中文显示问题

plt.rcparams['font.sans-serif'] = ['simhei']  # 解决中文乱码
plt.rcparams['axes.unicode_minus'] = false  # 解决负号显示问题

柱状图重叠

  • 调整bar_width参数
  • 使用x_indexes控制位置
  • 添加透明度alpha=0.8

大数据集优化

  • 使用ax.bar()替代plt.bar()提高性能
  • 对于超过50个类别的数据,考虑使用水平柱状图

通过掌握这些技巧,你可以创建出适用于商业报告、学术论文和数据仪表盘的专业级柱状图。matplotlib的强大功能结合python的数据处理能力,使数据可视化变得既灵活又高效!

总结与扩展

本文从基础柱状图到多组对比、堆叠柱状图,再到结合实际数据的绘制,覆盖了柱状图的核心用法。关键技巧总结如下:

  1. 单组数据用plt.bar(x, height),多组数据需调整x位置避免重叠;
  2. 堆叠柱状图通过bottom参数实现,适合展示部分与整体关系;
  3. 样式美化的核心是:清晰的标题 / 标签、合理的颜色搭配、辅助网格线和数据标签;
  4. 结合pandas可高效处理实际业务数据,降低代码复杂度。

实际应用中,可根据需求进一步探索动态柱状图(如plotly库)、3d 柱状图等扩展形式,让数据可视化更具表现力。

通过不断调整参数、尝试不同样式,你可以绘制出既美观又实用的柱状图,让数据传递更高效的信息。

以上就是python使用matplotlib绘制专业柱状图的完整指南的详细内容,更多关于python matplotlib绘制柱状图的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com