活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

matplotlib绘制条形图完全指南从基础语法到高级应用案例详解助你成为数据可视化专家

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-14 10:10:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

Matplotlib是Python中最流行的数据可视化库之一,它提供了丰富的绘图功能,能够帮助我们将数据转化为直观、易于理解的图形。在众多图表类型中,条形图(Bar Chart)是最常用的一种,它通过不同长度的条形来展示和比较各类别数据的大小关系。无论是展示销售数据、比较不同产品的性能,还是分析调查结果,条形图都能发挥重要作用。

本指南将带你从matplotlib条形图的基础语法开始,逐步深入到各种高级应用案例,帮助你全面掌握条形图的绘制技巧,最终成为数据可视化专家。无论你是数据分析师、科学家,还是只是对数据可视化感兴趣的初学者,本指南都能为你提供实用的知识和技能。

基础语法

在开始绘制条形图之前,我们需要先导入必要的库并准备一些基础数据。

导入库和准备数据
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 准备数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values = [23, 45, 56, 78, 32]
  6. # 创建图形和坐标轴
  7. fig, ax = plt.subplots()
复制代码

基本条形图绘制

使用bar()函数可以轻松创建基本的垂直条形图:
  1. # 绘制基本条形图
  2. ax.bar(categories, values)
  3. # 显示图形
  4. plt.show()
复制代码

这段简单的代码会生成一个包含五个类别的垂直条形图,每个条形的高度对应其值。

添加标题和标签

为了让图表更加清晰易读,我们通常需要添加标题和轴标签:
  1. # 绘制条形图
  2. ax.bar(categories, values)
  3. # 添加标题和轴标签
  4. ax.set_title('基本条形图示例')
  5. ax.set_xlabel('类别')
  6. ax.set_ylabel('值')
  7. # 显示图形
  8. plt.show()
复制代码

调整图形大小

有时候默认的图形大小可能不适合我们的需求,我们可以使用figure()函数的figsize参数来调整图形大小:
  1. # 创建指定大小的图形
  2. plt.figure(figsize=(10, 6))
  3. # 绘制条形图
  4. plt.bar(categories, values)
  5. # 添加标题和轴标签
  6. plt.title('调整大小的条形图')
  7. plt.xlabel('类别')
  8. plt.ylabel('值')
  9. # 显示图形
  10. plt.show()
复制代码

条形图类型

Matplotlib提供了多种类型的条形图,以适应不同的数据展示需求。下面我们将介绍几种常见的条形图类型。

垂直条形图

垂直条形图是最常见的条形图类型,条形垂直向上延伸。我们已经在基础语法中看到了简单的垂直条形图,下面是一个更完整的例子:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制垂直条形图
  8. bars = plt.bar(categories, sales, color='skyblue')
  9. # 添加数据标签
  10. for bar in bars:
  11.     height = bar.get_height()
  12.     plt.text(bar.get_x() + bar.get_width()/2., height,
  13.              f'{height}',
  14.              ha='center', va='bottom')
  15. # 添加标题和标签
  16. plt.title('水果销售数据', fontsize=14)
  17. plt.xlabel('水果种类', fontsize=12)
  18. plt.ylabel('销售量', fontsize=12)
  19. # 显示网格线
  20. plt.grid(axis='y', linestyle='--', alpha=0.7)
  21. # 调整布局
  22. plt.tight_layout()
  23. # 显示图形
  24. plt.show()
复制代码

水平条形图

当类别名称较长或类别数量较多时,水平条形图可能更适合展示数据。使用barh()函数可以创建水平条形图:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['项目A', '项目B', '项目C', '项目D', '项目E']
  4. values = [23, 45, 56, 78, 32]
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制水平条形图
  8. bars = plt.barh(categories, values, color='lightgreen')
  9. # 添加数据标签
  10. for bar in bars:
  11.     width = bar.get_width()
  12.     plt.text(width, bar.get_y() + bar.get_height()/2.,
  13.              f'{width}',
  14.              ha='left', va='center')
  15. # 添加标题和标签
  16. plt.title('项目数据对比', fontsize=14)
  17. plt.xlabel('数值', fontsize=12)
  18. plt.ylabel('项目名称', fontsize=12)
  19. # 显示网格线
  20. plt.grid(axis='x', linestyle='--', alpha=0.7)
  21. # 调整布局
  22. plt.tight_layout()
  23. # 显示图形
  24. plt.show()
复制代码

堆叠条形图

堆叠条形图适用于展示每个类别的组成部分及其总和。每个条形由多个部分堆叠而成,不同部分用不同颜色表示:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  5. product_A = [20, 35, 30, 35]
  6. product_B = [15, 25, 20, 30]
  7. product_C = [10, 20, 15, 25]
  8. # 创建图形
  9. plt.figure(figsize=(10, 6))
  10. # 绘制堆叠条形图
  11. plt.bar(categories, product_A, label='产品A', color='skyblue')
  12. plt.bar(categories, product_B, bottom=product_A, label='产品B', color='lightgreen')
  13. plt.bar(categories, product_C, bottom=np.array(product_A) + np.array(product_B),
  14.         label='产品C', color='salmon')
  15. # 添加标题和标签
  16. plt.title('季度产品销售堆叠图', fontsize=14)
  17. plt.xlabel('季度', fontsize=12)
  18. plt.ylabel('销售量', fontsize=12)
  19. # 添加图例
  20. plt.legend()
  21. # 显示网格线
  22. plt.grid(axis='y', linestyle='--', alpha=0.7)
  23. # 调整布局
  24. plt.tight_layout()
  25. # 显示图形
  26. plt.show()
复制代码

分组条形图

分组条形图用于比较不同组别在多个类别上的表现。每个类别有多个并排的条形,分别代表不同的组别:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  5. product_A = [20, 35, 30, 35]
  6. product_B = [15, 25, 20, 30]
  7. product_C = [10, 20, 15, 25]
  8. # 设置条形宽度和位置
  9. bar_width = 0.25
  10. r1 = np.arange(len(categories))
  11. r2 = [x + bar_width for x in r1]
  12. r3 = [x + bar_width for x in r2]
  13. # 创建图形
  14. plt.figure(figsize=(10, 6))
  15. # 绘制分组条形图
  16. plt.bar(r1, product_A, width=bar_width, label='产品A', color='skyblue')
  17. plt.bar(r2, product_B, width=bar_width, label='产品B', color='lightgreen')
  18. plt.bar(r3, product_C, width=bar_width, label='产品C', color='salmon')
  19. # 添加标题和标签
  20. plt.title('季度产品销售分组图', fontsize=14)
  21. plt.xlabel('季度', fontsize=12)
  22. plt.ylabel('销售量', fontsize=12)
  23. # 设置x轴刻度标签
  24. plt.xticks([r + bar_width for r in range(len(categories))], categories)
  25. # 添加图例
  26. plt.legend()
  27. # 显示网格线
  28. plt.grid(axis='y', linestyle='--', alpha=0.7)
  29. # 调整布局
  30. plt.tight_layout()
  31. # 显示图形
  32. plt.show()
复制代码

自定义条形图

Matplotlib提供了丰富的选项来自定义条形图的外观,使其更加美观和信息丰富。

颜色设置

你可以为条形设置单一颜色、渐变色或根据数值映射不同颜色:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values = [23, 45, 56, 78, 32]
  6. # 创建图形
  7. plt.figure(figsize=(10, 6))
  8. # 使用单一颜色
  9. plt.subplot(2, 2, 1)
  10. plt.bar(categories, values, color='skyblue')
  11. plt.title('单一颜色')
  12. # 使用不同颜色
  13. plt.subplot(2, 2, 2)
  14. colors = ['red', 'blue', 'green', 'orange', 'purple']
  15. plt.bar(categories, values, color=colors)
  16. plt.title('不同颜色')
  17. # 使用颜色映射
  18. plt.subplot(2, 2, 3)
  19. cmap = plt.get_cmap('viridis')
  20. colors = cmap(np.linspace(0, 1, len(categories)))
  21. plt.bar(categories, values, color=colors)
  22. plt.title('颜色映射')
  23. # 根据值设置颜色
  24. plt.subplot(2, 2, 4)
  25. norm = plt.Normalize(min(values), max(values))
  26. cmap = plt.get_cmap('coolwarm')
  27. colors = cmap(norm(values))
  28. plt.bar(categories, values, color=colors)
  29. plt.title('基于值的颜色')
  30. # 调整布局
  31. plt.tight_layout()
  32. # 显示图形
  33. plt.show()
复制代码

条形宽度和间距

调整条形的宽度和间距可以使图表更加美观:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values = [23, 45, 56, 78, 32]
  6. # 创建图形
  7. plt.figure(figsize=(12, 6))
  8. # 默认宽度
  9. plt.subplot(1, 3, 1)
  10. plt.bar(categories, values)
  11. plt.title('默认宽度')
  12. # 较窄的条形
  13. plt.subplot(1, 3, 2)
  14. plt.bar(categories, values, width=0.5)
  15. plt.title('窄条形')
  16. # 较宽的条形
  17. plt.subplot(1, 3, 3)
  18. plt.bar(categories, values, width=0.9)
  19. plt.title('宽条形')
  20. # 调整布局
  21. plt.tight_layout()
  22. # 显示图形
  23. plt.show()
复制代码

添加数据标签

在条形上添加数据标签可以使图表更加直观:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制条形图
  8. bars = plt.bar(categories, sales, color='skyblue')
  9. # 添加数据标签
  10. for bar in bars:
  11.     height = bar.get_height()
  12.     plt.text(bar.get_x() + bar.get_width()/2., height,
  13.              f'{height}',
  14.              ha='center', va='bottom')
  15. # 添加标题和标签
  16. plt.title('水果销售数据', fontsize=14)
  17. plt.xlabel('水果种类', fontsize=12)
  18. plt.ylabel('销售量', fontsize=12)
  19. # 显示网格线
  20. plt.grid(axis='y', linestyle='--', alpha=0.7)
  21. # 调整布局
  22. plt.tight_layout()
  23. # 显示图形
  24. plt.show()
复制代码

添加误差线

误差线可以表示数据的不确定性或变异性:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values = [23, 45, 56, 78, 32]
  6. errors = [2, 3, 4, 5, 2]
  7. # 创建图形
  8. plt.figure(figsize=(10, 6))
  9. # 绘制带误差线的条形图
  10. plt.bar(categories, values, yerr=errors, capsize=5, color='skyblue')
  11. # 添加标题和标签
  12. plt.title('带误差线的条形图', fontsize=14)
  13. plt.xlabel('类别', fontsize=12)
  14. plt.ylabel('值', fontsize=12)
  15. # 显示网格线
  16. plt.grid(axis='y', linestyle='--', alpha=0.7)
  17. # 调整布局
  18. plt.tight_layout()
  19. # 显示图形
  20. plt.show()
复制代码

添加参考线

参考线可以帮助读者更好地理解数据:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. target = 50  # 目标销售量
  6. # 创建图形
  7. plt.figure(figsize=(10, 6))
  8. # 绘制条形图
  9. bars = plt.bar(categories, sales, color='skyblue')
  10. # 添加目标线
  11. plt.axhline(y=target, color='red', linestyle='--', linewidth=2, label='目标销售量')
  12. # 添加数据标签
  13. for bar in bars:
  14.     height = bar.get_height()
  15.     plt.text(bar.get_x() + bar.get_width()/2., height,
  16.              f'{height}',
  17.              ha='center', va='bottom')
  18. # 添加标题和标签
  19. plt.title('水果销售数据与目标对比', fontsize=14)
  20. plt.xlabel('水果种类', fontsize=12)
  21. plt.ylabel('销售量', fontsize=12)
  22. # 添加图例
  23. plt.legend()
  24. # 显示网格线
  25. plt.grid(axis='y', linestyle='--', alpha=0.7)
  26. # 调整布局
  27. plt.tight_layout()
  28. # 显示图形
  29. plt.show()
复制代码

高级应用

掌握了基础条形图的绘制方法后,我们可以探索一些更高级的应用,这些应用可以帮助我们更好地展示复杂的数据关系。

百分比堆叠条形图

百分比堆叠条形图可以展示各部分占总体的比例:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  5. product_A = [20, 35, 30, 35]
  6. product_B = [15, 25, 20, 30]
  7. product_C = [10, 20, 15, 25]
  8. # 计算总和
  9. totals = np.array(product_A) + np.array(product_B) + np.array(product_C)
  10. # 计算百分比
  11. product_A_percent = np.array(product_A) / totals * 100
  12. product_B_percent = np.array(product_B) / totals * 100
  13. product_C_percent = np.array(product_C) / totals * 100
  14. # 创建图形
  15. plt.figure(figsize=(10, 6))
  16. # 绘制百分比堆叠条形图
  17. plt.bar(categories, product_A_percent, label='产品A', color='skyblue')
  18. plt.bar(categories, product_B_percent, bottom=product_A_percent,
  19.         label='产品B', color='lightgreen')
  20. plt.bar(categories, product_C_percent,
  21.         bottom=product_A_percent + product_B_percent,
  22.         label='产品C', color='salmon')
  23. # 添加标题和标签
  24. plt.title('季度产品销售百分比堆叠图', fontsize=14)
  25. plt.xlabel('季度', fontsize=12)
  26. plt.ylabel('百分比 (%)', fontsize=12)
  27. # 设置y轴范围
  28. plt.ylim(0, 100)
  29. # 添加图例
  30. plt.legend()
  31. # 显示网格线
  32. plt.grid(axis='y', linestyle='--', alpha=0.7)
  33. # 调整布局
  34. plt.tight_layout()
  35. # 显示图形
  36. plt.show()
复制代码

漏斗图

漏斗图常用于展示转化率或流程中的逐步减少:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. stages = ['访问', '注册', '下载', '购买', '复购']
  5. values = [10000, 7000, 4000, 2000, 1000]
  6. percentages = [100, 70, 40, 20, 10]
  7. # 创建图形
  8. plt.figure(figsize=(10, 6))
  9. # 计算条形的宽度和位置
  10. max_width = 0.8
  11. bar_width = [max_width * (value / values[0]) for value in values]
  12. y_pos = np.arange(len(stages))
  13. # 绘制漏斗图
  14. for i, (stage, width, value, pct) in enumerate(zip(stages, bar_width, values, percentages)):
  15.     plt.barh(y_pos[i], width, height=0.6, align='center', color='skyblue')
  16.     plt.text(width/2, y_pos[i], f'{value} ({pct}%)',
  17.              ha='center', va='center', color='black', fontweight='bold')
  18. # 添加标题和标签
  19. plt.title('用户转化漏斗图', fontsize=14)
  20. plt.xlabel('相对宽度', fontsize=12)
  21. plt.ylabel('阶段', fontsize=12)
  22. # 设置y轴刻度
  23. plt.yticks(y_pos, stages)
  24. # 隐藏x轴刻度
  25. plt.xticks([])
  26. # 隐藏边框
  27. for spine in plt.gca().spines.values():
  28.     spine.set_visible(False)
  29. # 调整布局
  30. plt.tight_layout()
  31. # 显示图形
  32. plt.show()
复制代码

甘特图

甘特图常用于项目管理,展示任务的时间安排:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from datetime import datetime, timedelta
  4. # 任务数据
  5. tasks = [
  6.     {'name': '需求分析', 'start': 0, 'duration': 5},
  7.     {'name': '系统设计', 'start': 4, 'duration': 6},
  8.     {'name': '开发实现', 'start': 8, 'duration': 12},
  9.     {'name': '测试验证', 'start': 18, 'duration': 5},
  10.     {'name': '部署上线', 'start': 22, 'duration': 3}
  11. ]
  12. # 创建图形
  13. fig, ax = plt.subplots(figsize=(12, 6))
  14. # 绘制甘特图
  15. for i, task in enumerate(tasks):
  16.     ax.barh(i, task['duration'], left=task['start'], height=0.6,
  17.             align='center', color='skyblue', alpha=0.8)
  18.     ax.text(task['start'] + task['duration']/2, i, task['name'],
  19.             ha='center', va='center', color='black', fontweight='bold')
  20. # 添加标题和标签
  21. ax.set_title('项目甘特图', fontsize=14)
  22. ax.set_xlabel('天数', fontsize=12)
  23. ax.set_ylabel('任务', fontsize=12)
  24. # 设置y轴刻度
  25. ax.set_yticks(range(len(tasks)))
  26. ax.set_yticklabels([task['name'] for task in tasks])
  27. # 设置x轴范围
  28. ax.set_xlim(0, 25)
  29. # 显示网格线
  30. ax.grid(axis='x', linestyle='--', alpha=0.7)
  31. # 调整布局
  32. plt.tight_layout()
  33. # 显示图形
  34. plt.show()
复制代码

动态条形图

动态条形图可以展示数据随时间的变化:
  1. import matplotlib.pyplot as plt
  2. import matplotlib.animation as animation
  3. import numpy as np
  4. # 生成随机数据
  5. np.random.seed(42)
  6. categories = ['A', 'B', 'C', 'D', 'E']
  7. data = np.random.randint(1, 100, size=(10, len(categories)))
  8. # 创建图形
  9. fig, ax = plt.subplots(figsize=(10, 6))
  10. # 初始化条形图
  11. bars = ax.bar(categories, data[0], color='skyblue')
  12. # 设置y轴范围
  13. ax.set_ylim(0, 100)
  14. # 添加标题和标签
  15. ax.set_title('动态条形图', fontsize=14)
  16. ax.set_xlabel('类别', fontsize=12)
  17. ax.set_ylabel('值', fontsize=12)
  18. # 添加时间文本
  19. time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
  20. # 更新函数
  21. def update(frame):
  22.     for bar, value in zip(bars, data[frame]):
  23.         bar.set_height(value)
  24.     time_text.set_text(f'时间步: {frame+1}')
  25.     return bars + [time_text]
  26. # 创建动画
  27. ani = animation.FuncAnimation(fig, update, frames=len(data),
  28.                               interval=500, blit=True)
  29. # 显示动画
  30. plt.show()
  31. # 如果需要保存动画,可以使用以下代码
  32. # ani.save('dynamic_bar_chart.mp4', writer='ffmpeg', fps=2)
复制代码

带有子图的复杂条形图

有时候我们需要在一个图形中展示多个相关的条形图:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values_2020 = [23, 45, 56, 78, 32]
  6. values_2021 = [34, 56, 43, 65, 45]
  7. values_2022 = [45, 67, 54, 76, 56]
  8. # 创建图形和子图
  9. fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12), sharex=True)
  10. # 绘制2020年数据
  11. bars1 = ax1.bar(categories, values_2020, color='skyblue')
  12. ax1.set_title('2020年数据', fontsize=12)
  13. ax1.set_ylabel('值', fontsize=10)
  14. ax1.grid(axis='y', linestyle='--', alpha=0.7)
  15. # 添加数据标签
  16. for bar in bars1:
  17.     height = bar.get_height()
  18.     ax1.text(bar.get_x() + bar.get_width()/2., height,
  19.              f'{height}',
  20.              ha='center', va='bottom')
  21. # 绘制2021年数据
  22. bars2 = ax2.bar(categories, values_2021, color='lightgreen')
  23. ax2.set_title('2021年数据', fontsize=12)
  24. ax2.set_ylabel('值', fontsize=10)
  25. ax2.grid(axis='y', linestyle='--', alpha=0.7)
  26. # 添加数据标签
  27. for bar in bars2:
  28.     height = bar.get_height()
  29.     ax2.text(bar.get_x() + bar.get_width()/2., height,
  30.              f'{height}',
  31.              ha='center', va='bottom')
  32. # 绘制2022年数据
  33. bars3 = ax3.bar(categories, values_2022, color='salmon')
  34. ax3.set_title('2022年数据', fontsize=12)
  35. ax3.set_xlabel('类别', fontsize=12)
  36. ax3.set_ylabel('值', fontsize=10)
  37. ax3.grid(axis='y', linestyle='--', alpha=0.7)
  38. # 添加数据标签
  39. for bar in bars3:
  40.     height = bar.get_height()
  41.     ax3.text(bar.get_x() + bar.get_width()/2., height,
  42.              f'{height}',
  43.              ha='center', va='bottom')
  44. # 添加总标题
  45. fig.suptitle('三年数据对比', fontsize=16)
  46. # 调整布局
  47. plt.tight_layout(rect=[0, 0, 1, 0.96])
  48. # 显示图形
  49. plt.show()
复制代码

实际案例

让我们通过几个实际案例来展示条形图在真实数据分析中的应用。

案例一:销售数据分析

假设我们是一家零售公司,想要分析不同产品类别在各季度的销售情况:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. # 创建模拟数据
  5. np.random.seed(42)
  6. quarters = ['Q1', 'Q2', 'Q3', 'Q4']
  7. categories = ['电子产品', '服装', '家居', '食品', '图书']
  8. # 生成随机销售数据(单位:万元)
  9. data = np.random.randint(50, 200, size=(len(quarters), len(categories)))
  10. # 创建DataFrame
  11. df = pd.DataFrame(data, index=quarters, columns=categories)
  12. # 创建图形
  13. plt.figure(figsize=(12, 8))
  14. # 绘制分组条形图
  15. bar_width = 0.15
  16. r = np.arange(len(quarters))
  17. for i, category in enumerate(categories):
  18.     plt.bar(r + i * bar_width, df[category], width=bar_width, label=category)
  19. # 添加标题和标签
  20. plt.title('各季度产品类别销售对比', fontsize=16)
  21. plt.xlabel('季度', fontsize=12)
  22. plt.ylabel('销售额(万元)', fontsize=12)
  23. # 设置x轴刻度
  24. plt.xticks(r + bar_width * (len(categories) - 1) / 2, quarters)
  25. # 添加图例
  26. plt.legend()
  27. # 显示网格线
  28. plt.grid(axis='y', linestyle='--', alpha=0.7)
  29. # 调整布局
  30. plt.tight_layout()
  31. # 显示图形
  32. plt.show()
  33. # 绘制堆叠条形图
  34. plt.figure(figsize=(12, 8))
  35. bottom = np.zeros(len(quarters))
  36. for category in categories:
  37.     plt.bar(quarters, df[category], bottom=bottom, label=category)
  38.     bottom += df[category]
  39. # 添加标题和标签
  40. plt.title('各季度产品类别销售堆叠图', fontsize=16)
  41. plt.xlabel('季度', fontsize=12)
  42. plt.ylabel('销售额(万元)', fontsize=12)
  43. # 添加图例
  44. plt.legend()
  45. # 显示网格线
  46. plt.grid(axis='y', linestyle='--', alpha=0.7)
  47. # 调整布局
  48. plt.tight_layout()
  49. # 显示图形
  50. plt.show()
复制代码

案例二:学生成绩分析

假设我们是一位教师,想要分析班级学生在不同科目上的表现:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. # 创建模拟数据
  5. np.random.seed(42)
  6. subjects = ['数学', '语文', '英语', '物理', '化学', '生物']
  7. students = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  8. # 生成随机成绩数据
  9. data = np.random.randint(60, 100, size=(len(students), len(subjects)))
  10. # 创建DataFrame
  11. df = pd.DataFrame(data, index=students, columns=subjects)
  12. # 计算各科平均分
  13. avg_scores = df.mean()
  14. # 计算各科最高分和最低分
  15. max_scores = df.max()
  16. min_scores = df.min()
  17. # 创建图形
  18. plt.figure(figsize=(12, 8))
  19. # 绘制平均分条形图
  20. bars = plt.bar(subjects, avg_scores, color='skyblue', alpha=0.7, label='平均分')
  21. # 添加最高分和最低分标记
  22. plt.scatter(subjects, max_scores, color='red', s=100, label='最高分')
  23. plt.scatter(subjects, min_scores, color='green', s=100, label='最低分')
  24. # 添加数据标签
  25. for bar in bars:
  26.     height = bar.get_height()
  27.     plt.text(bar.get_x() + bar.get_width()/2., height,
  28.              f'{height:.1f}',
  29.              ha='center', va='bottom')
  30. # 添加标题和标签
  31. plt.title('各科目成绩分析', fontsize=16)
  32. plt.xlabel('科目', fontsize=12)
  33. plt.ylabel('分数', fontsize=12)
  34. # 设置y轴范围
  35. plt.ylim(50, 100)
  36. # 添加图例
  37. plt.legend()
  38. # 显示网格线
  39. plt.grid(axis='y', linestyle='--', alpha=0.7)
  40. # 调整布局
  41. plt.tight_layout()
  42. # 显示图形
  43. plt.show()
  44. # 绘制学生成绩热力图
  45. plt.figure(figsize=(12, 8))
  46. # 创建热力图
  47. im = plt.imshow(df, cmap='YlGnBu')
  48. # 添加颜色条
  49. cbar = plt.colorbar(im)
  50. cbar.set_label('分数', fontsize=12)
  51. # 设置刻度
  52. plt.xticks(np.arange(len(subjects)), subjects)
  53. plt.yticks(np.arange(len(students)), students)
  54. # 添加数据标签
  55. for i in range(len(students)):
  56.     for j in range(len(subjects)):
  57.         plt.text(j, i, df.iloc[i, j], ha="center", va="center", color="black")
  58. # 添加标题
  59. plt.title('学生成绩热力图', fontsize=16)
  60. # 调整布局
  61. plt.tight_layout()
  62. # 显示图形
  63. plt.show()
复制代码

案例三:网站流量分析

假设我们运营一个网站,想要分析不同渠道带来的流量和转化情况:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. # 创建模拟数据
  5. channels = ['直接访问', '搜索引擎', '社交媒体', '邮件营销', '广告投放']
  6. visitors = [12000, 18000, 9000, 6000, 8000]
  7. conversions = [1200, 1620, 450, 360, 400]
  8. conversion_rates = [c/v*100 for c, v in zip(conversions, visitors)]
  9. # 创建图形
  10. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
  11. # 绘制访问量条形图
  12. bars1 = ax1.bar(channels, visitors, color='skyblue')
  13. # 添加数据标签
  14. for bar in bars1:
  15.     height = bar.get_height()
  16.     ax1.text(bar.get_x() + bar.get_width()/2., height,
  17.              f'{height}',
  18.              ha='center', va='bottom')
  19. # 添加标题和标签
  20. ax1.set_title('各渠道访问量', fontsize=14)
  21. ax1.set_xlabel('渠道', fontsize=12)
  22. ax1.set_ylabel('访问量', fontsize=12)
  23. # 旋转x轴标签
  24. plt.setp(ax1.get_xticklabels(), rotation=45, ha='right')
  25. # 显示网格线
  26. ax1.grid(axis='y', linestyle='--', alpha=0.7)
  27. # 绘制转化率条形图
  28. bars2 = ax2.bar(channels, conversion_rates, color='lightgreen')
  29. # 添加数据标签
  30. for bar in bars2:
  31.     height = bar.get_height()
  32.     ax2.text(bar.get_x() + bar.get_width()/2., height,
  33.              f'{height:.1f}%',
  34.              ha='center', va='bottom')
  35. # 添加标题和标签
  36. ax2.set_title('各渠道转化率', fontsize=14)
  37. ax2.set_xlabel('渠道', fontsize=12)
  38. ax2.set_ylabel('转化率 (%)', fontsize=12)
  39. # 旋转x轴标签
  40. plt.setp(ax2.get_xticklabels(), rotation=45, ha='right')
  41. # 显示网格线
  42. ax2.grid(axis='y', linestyle='--', alpha=0.7)
  43. # 调整布局
  44. plt.tight_layout()
  45. # 显示图形
  46. plt.show()
  47. # 绘制访问量与转化量对比图
  48. plt.figure(figsize=(12, 6))
  49. # 设置条形宽度和位置
  50. bar_width = 0.35
  51. r1 = np.arange(len(channels))
  52. r2 = [x + bar_width for x in r1]
  53. # 绘制条形图
  54. plt.bar(r1, visitors, width=bar_width, label='访问量', color='skyblue')
  55. plt.bar(r2, conversions, width=bar_width, label='转化量', color='salmon')
  56. # 添加标题和标签
  57. plt.title('各渠道访问量与转化量对比', fontsize=14)
  58. plt.xlabel('渠道', fontsize=12)
  59. plt.ylabel('数量', fontsize=12)
  60. # 设置x轴刻度
  61. plt.xticks([r + bar_width/2 for r in range(len(channels))], channels)
  62. # 添加图例
  63. plt.legend()
  64. # 显示网格线
  65. plt.grid(axis='y', linestyle='--', alpha=0.7)
  66. # 调整布局
  67. plt.tight_layout()
  68. # 显示图形
  69. plt.show()
复制代码

最佳实践和技巧

在绘制条形图时,遵循一些最佳实践和技巧可以使你的图表更加专业和有效。

选择合适的条形图类型

根据你的数据和分析目的,选择最合适的条形图类型:

• 垂直条形图:适用于类别数量较少且类别名称较短的情况。
• 水平条形图:适用于类别数量较多或类别名称较长的情况。
• 堆叠条形图:适用于展示各部分占总体的比例和总和。
• 分组条形图:适用于比较不同组别在多个类别上的表现。

颜色选择

选择合适的颜色可以使你的图表更加美观和易于理解:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 数据
  4. categories = ['A', 'B', 'C', 'D', 'E']
  5. values = [23, 45, 56, 78, 32]
  6. # 创建图形
  7. plt.figure(figsize=(15, 10))
  8. # 使用单一颜色
  9. plt.subplot(2, 3, 1)
  10. plt.bar(categories, values, color='#4e79a7')  # 使用十六进制颜色代码
  11. plt.title('单一颜色')
  12. # 使用颜色映射
  13. plt.subplot(2, 3, 2)
  14. cmap = plt.get_cmap('viridis')
  15. colors = cmap(np.linspace(0, 1, len(categories)))
  16. plt.bar(categories, values, color=colors)
  17. plt.title('Viridis颜色映射')
  18. # 使用分类颜色
  19. plt.subplot(2, 3, 3)
  20. colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
  21. plt.bar(categories, values, color=colors)
  22. plt.title('分类颜色')
  23. # 使用渐变色
  24. plt.subplot(2, 3, 4)
  25. colors = plt.cm.Blues(np.linspace(0.3, 0.9, len(categories)))
  26. plt.bar(categories, values, color=colors)
  27. plt.title('蓝色渐变')
  28. # 根据值设置颜色
  29. plt.subplot(2, 3, 5)
  30. norm = plt.Normalize(min(values), max(values))
  31. cmap = plt.get_cmap('coolwarm')
  32. colors = cmap(norm(values))
  33. plt.bar(categories, values, color=colors)
  34. plt.title('基于值的颜色')
  35. # 使用透明度
  36. plt.subplot(2, 3, 6)
  37. plt.bar(categories, values, color='skyblue', alpha=0.7)
  38. plt.title('使用透明度')
  39. # 调整布局
  40. plt.tight_layout()
  41. # 显示图形
  42. plt.show()
复制代码

标签和标题

清晰、简洁的标签和标题可以帮助读者更好地理解图表:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制条形图
  8. bars = plt.bar(categories, sales, color='skyblue')
  9. # 添加数据标签
  10. for bar in bars:
  11.     height = bar.get_height()
  12.     plt.text(bar.get_x() + bar.get_width()/2., height,
  13.              f'{height}',
  14.              ha='center', va='bottom')
  15. # 添加标题和标签
  16. plt.title('2023年水果销售数据', fontsize=16, pad=20)  # pad参数控制标题与图表的间距
  17. plt.xlabel('水果种类', fontsize=12, labelpad=10)  # labelpad参数控制标签与轴的间距
  18. plt.ylabel('销售量(吨)', fontsize=12, labelpad=10)
  19. # 添加注释
  20. plt.annotate('最高销量', xy=('葡萄', 89), xytext=('葡萄', 95),
  21.              arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8),
  22.              ha='center')
  23. # 显示网格线
  24. plt.grid(axis='y', linestyle='--', alpha=0.7)
  25. # 调整布局
  26. plt.tight_layout()
  27. # 显示图形
  28. plt.show()
复制代码

排序条形图

对条形图进行排序可以使数据更加直观:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. # 按销售量排序
  6. sorted_indices = sorted(range(len(sales)), key=lambda i: sales[i])
  7. sorted_categories = [categories[i] for i in sorted_indices]
  8. sorted_sales = [sales[i] for i in sorted_indices]
  9. # 创建图形
  10. plt.figure(figsize=(10, 6))
  11. # 绘制排序后的条形图
  12. bars = plt.bar(sorted_categories, sorted_sales, color='skyblue')
  13. # 添加数据标签
  14. for bar in bars:
  15.     height = bar.get_height()
  16.     plt.text(bar.get_x() + bar.get_width()/2., height,
  17.              f'{height}',
  18.              ha='center', va='bottom')
  19. # 添加标题和标签
  20. plt.title('水果销售数据(按销量排序)', fontsize=14)
  21. plt.xlabel('水果种类', fontsize=12)
  22. plt.ylabel('销售量', fontsize=12)
  23. # 显示网格线
  24. plt.grid(axis='y', linestyle='--', alpha=0.7)
  25. # 调整布局
  26. plt.tight_layout()
  27. # 显示图形
  28. plt.show()
复制代码

处理长类别名称

当类别名称较长时,可以采用以下方法提高可读性:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['这是一个非常长的类别名称A', '这是一个非常长的类别名称B',
  4.               '这是一个非常长的类别名称C', '这是一个非常长的类别名称D',
  5.               '这是一个非常长的类别名称E']
  6. values = [23, 45, 56, 78, 32]
  7. # 创建图形
  8. plt.figure(figsize=(12, 8))
  9. # 方法1:使用水平条形图
  10. plt.subplot(2, 1, 1)
  11. bars = plt.barh(categories, values, color='skyblue')
  12. # 添加数据标签
  13. for bar in bars:
  14.     width = bar.get_width()
  15.     plt.text(width, bar.get_y() + bar.get_height()/2.,
  16.              f'{width}',
  17.              ha='left', va='center')
  18. # 添加标题和标签
  19. plt.title('水平条形图处理长类别名称', fontsize=14)
  20. plt.xlabel('值', fontsize=12)
  21. plt.ylabel('类别', fontsize=12)
  22. # 显示网格线
  23. plt.grid(axis='x', linestyle='--', alpha=0.7)
  24. # 方法2:旋转x轴标签
  25. plt.subplot(2, 1, 2)
  26. bars = plt.bar(categories, values, color='lightgreen')
  27. # 添加数据标签
  28. for bar in bars:
  29.     height = bar.get_height()
  30.     plt.text(bar.get_x() + bar.get_width()/2., height,
  31.              f'{height}',
  32.              ha='center', va='bottom')
  33. # 添加标题和标签
  34. plt.title('旋转x轴标签处理长类别名称', fontsize=14)
  35. plt.xlabel('类别', fontsize=12)
  36. plt.ylabel('值', fontsize=12)
  37. # 旋转x轴标签
  38. plt.xticks(rotation=45, ha='right')
  39. # 显示网格线
  40. plt.grid(axis='y', linestyle='--', alpha=0.7)
  41. # 调整布局
  42. plt.tight_layout()
  43. # 显示图形
  44. plt.show()
复制代码

添加数据来源和注释

专业的图表通常包含数据来源和必要的注释:
  1. import matplotlib.pyplot as plt
  2. # 数据
  3. categories = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
  4. sales = [45, 67, 34, 89, 56]
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制条形图
  8. bars = plt.bar(categories, sales, color='skyblue')
  9. # 添加数据标签
  10. for bar in bars:
  11.     height = bar.get_height()
  12.     plt.text(bar.get_x() + bar.get_width()/2., height,
  13.              f'{height}',
  14.              ha='center', va='bottom')
  15. # 添加标题和标签
  16. plt.title('2023年水果销售数据', fontsize=16, pad=20)
  17. plt.xlabel('水果种类', fontsize=12, labelpad=10)
  18. plt.ylabel('销售量(吨)', fontsize=12, labelpad=10)
  19. # 添加注释
  20. plt.figtext(0.5, 0.01, '数据来源:XX市场调研公司 2023年报告',
  21.             ha='center', fontsize=10, color='gray')
  22. # 添加说明
  23. plt.figtext(0.5, 0.95, '注:数据仅用于演示目的',
  24.             ha='center', fontsize=10, color='gray')
  25. # 显示网格线
  26. plt.grid(axis='y', linestyle='--', alpha=0.7)
  27. # 调整布局
  28. plt.tight_layout(rect=[0, 0.03, 1, 0.95])  # 为底部和顶部的注释留出空间
  29. # 显示图形
  30. plt.show()
复制代码

总结

通过本指南,我们全面介绍了使用matplotlib绘制条形图的各种方法和技巧。从基础的垂直和水平条形图,到更复杂的堆叠条形图、分组条形图,再到高级应用如百分比堆叠条形图、漏斗图、甘特图和动态条形图,我们涵盖了条形图的各个方面。

我们还探讨了如何自定义条形图的外观,包括颜色设置、条形宽度和间距调整、添加数据标签、误差线和参考线等。通过实际案例,我们展示了条形图在销售数据分析、学生成绩分析和网站流量分析等领域的应用。

最后,我们分享了一些最佳实践和技巧,帮助你创建更加专业和有效的条形图。记住,好的数据可视化不仅仅是美观,更重要的是能够清晰、准确地传达信息。

随着你对matplotlib条形图的掌握越来越深入,你将能够更加自信地应对各种数据可视化挑战,成为真正的数据可视化专家。继续探索和学习,你会发现matplotlib的强大功能远不止于此,它还有更多等待你去发现的精彩特性。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则