简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:为庆祝网站一周年,将在5.1日与5.2日开放注册,具体信息请见后续详细公告
04-22 00:04
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

利用Matplotlib在Python中创建专业条形图的实例教程涵盖数据准备图表定制和美化技巧

SunJu_FaceMall

3万

主题

1158

科技点

3万

积分

白金月票

碾压王

积分
32796

立华奏

发表于 2025-10-5 11:10:00 | 显示全部楼层 |阅读模式

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

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

x
简介

Matplotlib是Python中最流行的数据可视化库之一,它提供了强大的绘图功能,能够创建各种静态、动态和交互式的图表。在数据分析和展示中,条形图是一种常用的图表类型,它能够直观地比较不同类别的数据大小。本文将详细介绍如何使用Matplotlib创建专业的条形图,从数据准备到图表定制和美化技巧,帮助读者掌握条形图的完整制作流程。

数据准备

导入必要的库

在开始创建条形图之前,我们需要导入必要的Python库:
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import matplotlib as mpl
  5. from matplotlib.ticker import PercentFormatter
  6. # 设置中文字体,防止中文显示乱码
  7. plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
  8. plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
复制代码

准备数据

数据是图表的基础,我们可以从多种来源获取数据。以下是几种常见的数据准备方式:
  1. # 简单的列表数据
  2. categories = ['产品A', '产品B', '产品C', '产品D', '产品E']
  3. values = [23, 56, 41, 62, 19]
  4. # 使用NumPy数组
  5. np_categories = np.array(['产品A', '产品B', '产品C', '产品D', '产品E'])
  6. np_values = np.array([23, 56, 41, 62, 19])
复制代码
  1. # 创建DataFrame
  2. data = {
  3.     '产品': ['产品A', '产品B', '产品C', '产品D', '产品E'],
  4.     '销售额': [23, 56, 41, 62, 19],
  5.     '利润': [5, 12, 8, 15, 3]
  6. }
  7. df = pd.DataFrame(data)
  8. # 从CSV文件读取数据
  9. # df = pd.read_csv('sales_data.csv')
复制代码

在实际应用中,我们经常需要对数据进行预处理:
  1. # 数据排序
  2. df_sorted = df.sort_values('销售额', ascending=False)
  3. # 数据筛选
  4. high_sales = df[df['销售额'] > 30]
  5. # 数据分组和聚合
  6. # 假设我们有一个包含更多数据的DataFrame
  7. # grouped_data = df.groupby('类别')['销售额'].sum()
复制代码

基础条形图创建

创建简单的垂直条形图
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制条形图
  4. bars = ax.bar(categories, values)
  5. # 显示图表
  6. plt.tight_layout()
  7. plt.show()
复制代码

创建简单的水平条形图
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制水平条形图
  4. bars = ax.barh(categories, values)
  5. # 显示图表
  6. plt.tight_layout()
  7. plt.show()
复制代码

使用Pandas数据创建条形图
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 使用DataFrame数据绘制条形图
  4. bars = ax.bar(df['产品'], df['销售额'])
  5. # 显示图表
  6. plt.tight_layout()
  7. plt.show()
复制代码

图表定制

添加标题和标签
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制条形图
  4. bars = ax.bar(categories, values)
  5. # 添加标题和标签
  6. ax.set_title('产品销售额对比', fontsize=16, pad=20)
  7. ax.set_xlabel('产品名称', fontsize=12)
  8. ax.set_ylabel('销售额(万元)', fontsize=12)
  9. # 显示图表
  10. plt.tight_layout()
  11. plt.show()
复制代码

调整条形颜色和样式
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 定义颜色列表
  4. colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
  5. # 绘制条形图并设置颜色
  6. bars = ax.bar(categories, values, color=colors, edgecolor='black', linewidth=1.2)
  7. # 添加标题和标签
  8. ax.set_title('产品销售额对比', fontsize=16, pad=20)
  9. ax.set_xlabel('产品名称', fontsize=12)
  10. ax.set_ylabel('销售额(万元)', fontsize=12)
  11. # 显示图表
  12. plt.tight_layout()
  13. plt.show()
复制代码

添加数据标签
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制条形图
  4. bars = ax.bar(categories, values, color=colors, edgecolor='black', linewidth=1.2)
  5. # 添加数据标签
  6. for bar in bars:
  7.     height = bar.get_height()
  8.     ax.text(bar.get_x() + bar.get_width()/2., height,
  9.             f'{height}',
  10.             ha='center', va='bottom', fontsize=10)
  11. # 添加标题和标签
  12. ax.set_title('产品销售额对比', fontsize=16, pad=20)
  13. ax.set_xlabel('产品名称', fontsize=12)
  14. ax.set_ylabel('销售额(万元)', fontsize=12)
  15. # 显示图表
  16. plt.tight_layout()
  17. plt.show()
复制代码

调整坐标轴范围和刻度
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制条形图
  4. bars = ax.bar(categories, values, color=colors, edgecolor='black', linewidth=1.2)
  5. # 添加数据标签
  6. for bar in bars:
  7.     height = bar.get_height()
  8.     ax.text(bar.get_x() + bar.get_width()/2., height,
  9.             f'{height}',
  10.             ha='center', va='bottom', fontsize=10)
  11. # 添加标题和标签
  12. ax.set_title('产品销售额对比', fontsize=16, pad=20)
  13. ax.set_xlabel('产品名称', fontsize=12)
  14. ax.set_ylabel('销售额(万元)', fontsize=12)
  15. # 设置Y轴范围
  16. ax.set_ylim(0, 70)
  17. # 设置Y轴刻度
  18. ax.set_yticks(np.arange(0, 71, 10))
  19. # 显示图表
  20. plt.tight_layout()
  21. plt.show()
复制代码

添加网格线
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 绘制条形图
  4. bars = ax.bar(categories, values, color=colors, edgecolor='black', linewidth=1.2)
  5. # 添加数据标签
  6. for bar in bars:
  7.     height = bar.get_height()
  8.     ax.text(bar.get_x() + bar.get_width()/2., height,
  9.             f'{height}',
  10.             ha='center', va='bottom', fontsize=10)
  11. # 添加标题和标签
  12. ax.set_title('产品销售额对比', fontsize=16, pad=20)
  13. ax.set_xlabel('产品名称', fontsize=12)
  14. ax.set_ylabel('销售额(万元)', fontsize=12)
  15. # 设置Y轴范围和刻度
  16. ax.set_ylim(0, 70)
  17. ax.set_yticks(np.arange(0, 71, 10))
  18. # 添加网格线
  19. ax.grid(axis='y', linestyle='--', alpha=0.7)
  20. # 显示图表
  21. plt.tight_layout()
  22. plt.show()
复制代码

美化技巧

使用专业配色方案
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 使用专业配色方案
  4. colors = plt.cm.Set3(np.linspace(0, 1, len(categories)))
  5. # 绘制条形图
  6. bars = ax.bar(categories, values, color=colors, edgecolor='white', linewidth=1.2)
  7. # 添加数据标签
  8. for bar in bars:
  9.     height = bar.get_height()
  10.     ax.text(bar.get_x() + bar.get_width()/2., height,
  11.             f'{height}',
  12.             ha='center', va='bottom', fontsize=10, fontweight='bold')
  13. # 添加标题和标签
  14. ax.set_title('产品销售额对比', fontsize=16, pad=20, fontweight='bold')
  15. ax.set_xlabel('产品名称', fontsize=12)
  16. ax.set_ylabel('销售额(万元)', fontsize=12)
  17. # 设置Y轴范围和刻度
  18. ax.set_ylim(0, 70)
  19. ax.set_yticks(np.arange(0, 71, 10))
  20. # 添加网格线
  21. ax.grid(axis='y', linestyle='--', alpha=0.7)
  22. # 设置背景色
  23. ax.set_facecolor('#f8f9fa')
  24. # 显示图表
  25. plt.tight_layout()
  26. plt.show()
复制代码

添加图例和注释
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 使用专业配色方案
  4. colors = plt.cm.Set3(np.linspace(0, 1, len(categories)))
  5. # 绘制条形图
  6. bars = ax.bar(categories, values, color=colors, edgecolor='white', linewidth=1.2)
  7. # 添加数据标签
  8. for bar in bars:
  9.     height = bar.get_height()
  10.     ax.text(bar.get_x() + bar.get_width()/2., height,
  11.             f'{height}',
  12.             ha='center', va='bottom', fontsize=10, fontweight='bold')
  13. # 添加标题和标签
  14. ax.set_title('产品销售额对比', fontsize=16, pad=20, fontweight='bold')
  15. ax.set_xlabel('产品名称', fontsize=12)
  16. ax.set_ylabel('销售额(万元)', fontsize=12)
  17. # 设置Y轴范围和刻度
  18. ax.set_ylim(0, 70)
  19. ax.set_yticks(np.arange(0, 71, 10))
  20. # 添加网格线
  21. ax.grid(axis='y', linestyle='--', alpha=0.7)
  22. # 设置背景色
  23. ax.set_facecolor('#f8f9fa')
  24. # 添加注释
  25. ax.annotate('最高销售额', xy=('产品D', 62), xytext=('产品D', 65),
  26.             arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8),
  27.             ha='center', fontsize=10, fontweight='bold')
  28. # 显示图表
  29. plt.tight_layout()
  30. plt.show()
复制代码

调整条形宽度和间距
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 使用专业配色方案
  4. colors = plt.cm.Set3(np.linspace(0, 1, len(categories)))
  5. # 绘制条形图,调整宽度
  6. bar_width = 0.6  # 条形宽度
  7. bars = ax.bar(categories, values, color=colors, edgecolor='white',
  8.               linewidth=1.2, width=bar_width)
  9. # 添加数据标签
  10. for bar in bars:
  11.     height = bar.get_height()
  12.     ax.text(bar.get_x() + bar.get_width()/2., height,
  13.             f'{height}',
  14.             ha='center', va='bottom', fontsize=10, fontweight='bold')
  15. # 添加标题和标签
  16. ax.set_title('产品销售额对比', fontsize=16, pad=20, fontweight='bold')
  17. ax.set_xlabel('产品名称', fontsize=12)
  18. ax.set_ylabel('销售额(万元)', fontsize=12)
  19. # 设置Y轴范围和刻度
  20. ax.set_ylim(0, 70)
  21. ax.set_yticks(np.arange(0, 71, 10))
  22. # 添加网格线
  23. ax.grid(axis='y', linestyle='--', alpha=0.7)
  24. # 设置背景色
  25. ax.set_facecolor('#f8f9fa')
  26. # 调整X轴标签的位置
  27. ax.set_xticks(np.arange(len(categories)))
  28. ax.set_xticklabels(categories)
  29. # 显示图表
  30. plt.tight_layout()
  31. plt.show()
复制代码

添加渐变效果
  1. # 创建图形和坐标轴
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. # 创建渐变色
  4. from matplotlib.colors import LinearSegmentedColormap
  5. cmap = LinearSegmentedColormap.from_list('custom', ['#1f77b4', '#aec7e8'], N=100)
  6. # 绘制条形图
  7. bars = ax.bar(categories, values, edgecolor='white', linewidth=1.2)
  8. # 为每个条形设置渐变色
  9. for bar, value in zip(bars, values):
  10.     # 归一化值到0-1范围
  11.     norm_value = value / max(values)
  12.     # 设置颜色
  13.     bar.set_color(cmap(norm_value))
  14. # 添加数据标签
  15. for bar in bars:
  16.     height = bar.get_height()
  17.     ax.text(bar.get_x() + bar.get_width()/2., height,
  18.             f'{height}',
  19.             ha='center', va='bottom', fontsize=10, fontweight='bold')
  20. # 添加标题和标签
  21. ax.set_title('产品销售额对比', fontsize=16, pad=20, fontweight='bold')
  22. ax.set_xlabel('产品名称', fontsize=12)
  23. ax.set_ylabel('销售额(万元)', fontsize=12)
  24. # 设置Y轴范围和刻度
  25. ax.set_ylim(0, 70)
  26. ax.set_yticks(np.arange(0, 71, 10))
  27. # 添加网格线
  28. ax.grid(axis='y', linestyle='--', alpha=0.7)
  29. # 设置背景色
  30. ax.set_facecolor('#f8f9fa')
  31. # 显示图表
  32. plt.tight_layout()
  33. plt.show()
复制代码

高级条形图类型

分组条形图
  1. # 准备数据
  2. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  3. product_A = [23, 26, 30, 28]
  4. product_B = [15, 18, 22, 25]
  5. product_C = [12, 16, 19, 21]
  6. # 创建图形和坐标轴
  7. fig, ax = plt.subplots(figsize=(12, 6))
  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. bars1 = ax.bar(r1, product_A, color='#1f77b4', width=bar_width, edgecolor='white', label='产品A')
  15. bars2 = ax.bar(r2, product_B, color='#ff7f0e', width=bar_width, edgecolor='white', label='产品B')
  16. bars3 = ax.bar(r3, product_C, color='#2ca02c', width=bar_width, edgecolor='white', label='产品C')
  17. # 添加数据标签
  18. def add_labels(bars):
  19.     for bar in bars:
  20.         height = bar.get_height()
  21.         ax.text(bar.get_x() + bar.get_width()/2., height,
  22.                 f'{height}',
  23.                 ha='center', va='bottom', fontsize=9)
  24. add_labels(bars1)
  25. add_labels(bars2)
  26. add_labels(bars3)
  27. # 添加标题和标签
  28. ax.set_title('季度产品销售额对比', fontsize=16, pad=20, fontweight='bold')
  29. ax.set_xlabel('季度', fontsize=12)
  30. ax.set_ylabel('销售额(万元)', fontsize=12)
  31. # 设置X轴刻度和标签
  32. ax.set_xticks([r + bar_width for r in range(len(categories))])
  33. ax.set_xticklabels(categories)
  34. # 添加图例
  35. ax.legend()
  36. # 添加网格线
  37. ax.grid(axis='y', linestyle='--', alpha=0.7)
  38. # 设置背景色
  39. ax.set_facecolor('#f8f9fa')
  40. # 显示图表
  41. plt.tight_layout()
  42. plt.show()
复制代码

堆叠条形图
  1. # 准备数据
  2. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  3. product_A = [23, 26, 30, 28]
  4. product_B = [15, 18, 22, 25]
  5. product_C = [12, 16, 19, 21]
  6. # 创建图形和坐标轴
  7. fig, ax = plt.subplots(figsize=(12, 6))
  8. # 绘制堆叠条形图
  9. bars1 = ax.bar(categories, product_A, color='#1f77b4', label='产品A')
  10. bars2 = ax.bar(categories, product_B, bottom=product_A, color='#ff7f0e', label='产品B')
  11. bars3 = ax.bar(categories, product_C, bottom=np.array(product_A) + np.array(product_B),
  12.               color='#2ca02c', label='产品C')
  13. # 添加数据标签
  14. def add_stacked_labels(bars, bottom_values=None):
  15.     for i, bar in enumerate(bars):
  16.         height = bar.get_height()
  17.         if bottom_values is None:
  18.             y = height / 2
  19.         else:
  20.             y = bottom_values[i] + height / 2
  21.         ax.text(bar.get_x() + bar.get_width()/2., y,
  22.                 f'{height}',
  23.                 ha='center', va='center', fontsize=9, color='white', fontweight='bold')
  24. add_stacked_labels(bars1)
  25. add_stacked_labels(bars2, product_A)
  26. add_stacked_labels(bars3, np.array(product_A) + np.array(product_B))
  27. # 添加总数值标签
  28. totals = np.array(product_A) + np.array(product_B) + np.array(product_C)
  29. for i, total in enumerate(totals):
  30.     ax.text(i, total + 1,
  31.             f'总计: {total}',
  32.             ha='center', va='bottom', fontsize=9, fontweight='bold')
  33. # 添加标题和标签
  34. ax.set_title('季度产品销售额堆叠对比', fontsize=16, pad=20, fontweight='bold')
  35. ax.set_xlabel('季度', fontsize=12)
  36. ax.set_ylabel('销售额(万元)', fontsize=12)
  37. # 添加图例
  38. ax.legend()
  39. # 添加网格线
  40. ax.grid(axis='y', linestyle='--', alpha=0.7)
  41. # 设置背景色
  42. ax.set_facecolor('#f8f9fa')
  43. # 显示图表
  44. plt.tight_layout()
  45. plt.show()
复制代码

百分比堆叠条形图
  1. # 准备数据
  2. categories = ['Q1', 'Q2', 'Q3', 'Q4']
  3. product_A = [23, 26, 30, 28]
  4. product_B = [15, 18, 22, 25]
  5. product_C = [12, 16, 19, 21]
  6. # 计算百分比
  7. totals = np.array(product_A) + np.array(product_B) + np.array(product_C)
  8. product_A_pct = np.array(product_A) / totals * 100
  9. product_B_pct = np.array(product_B) / totals * 100
  10. product_C_pct = np.array(product_C) / totals * 100
  11. # 创建图形和坐标轴
  12. fig, ax = plt.subplots(figsize=(12, 6))
  13. # 绘制百分比堆叠条形图
  14. bars1 = ax.bar(categories, product_A_pct, color='#1f77b4', label='产品A')
  15. bars2 = ax.bar(categories, product_B_pct, bottom=product_A_pct, color='#ff7f0e', label='产品B')
  16. bars3 = ax.bar(categories, product_C_pct, bottom=product_A_pct + product_B_pct,
  17.               color='#2ca02c', label='产品C')
  18. # 添加数据标签
  19. def add_percentage_labels(bars, bottom_values=None):
  20.     for i, bar in enumerate(bars):
  21.         height = bar.get_height()
  22.         if bottom_values is None:
  23.             y = height / 2
  24.         else:
  25.             y = bottom_values[i] + height / 2
  26.         ax.text(bar.get_x() + bar.get_width()/2., y,
  27.                 f'{height:.1f}%',
  28.                 ha='center', va='center', fontsize=9, color='white', fontweight='bold')
  29. add_percentage_labels(bars1)
  30. add_percentage_labels(bars2, product_A_pct)
  31. add_percentage_labels(bars3, product_A_pct + product_B_pct)
  32. # 添加标题和标签
  33. ax.set_title('季度产品销售额占比', fontsize=16, pad=20, fontweight='bold')
  34. ax.set_xlabel('季度', fontsize=12)
  35. ax.set_ylabel('百分比 (%)', fontsize=12)
  36. # 设置Y轴为百分比格式
  37. ax.yaxis.set_major_formatter(PercentFormatter())
  38. # 添加图例
  39. ax.legend()
  40. # 添加网格线
  41. ax.grid(axis='y', linestyle='--', alpha=0.7)
  42. # 设置背景色
  43. ax.set_facecolor('#f8f9fa')
  44. # 显示图表
  45. plt.tight_layout()
  46. plt.show()
复制代码

水平分组条形图
  1. # 准备数据
  2. categories = ['产品A', '产品B', '产品C', '产品D', '产品E']
  3. q1_values = [23, 15, 12, 18, 8]
  4. q2_values = [26, 18, 16, 20, 10]
  5. q3_values = [30, 22, 19, 24, 14]
  6. q4_values = [28, 25, 21, 22, 12]
  7. # 创建图形和坐标轴
  8. fig, ax = plt.subplots(figsize=(12, 8))
  9. # 设置条形高度和位置
  10. bar_height = 0.2
  11. r1 = np.arange(len(categories))
  12. r2 = [x + bar_height for x in r1]
  13. r3 = [x + bar_height for x in r2]
  14. r4 = [x + bar_height for x in r3]
  15. # 绘制水平分组条形图
  16. bars1 = ax.barh(r1, q1_values, color='#1f77b4', height=bar_height, label='Q1')
  17. bars2 = ax.barh(r2, q2_values, color='#ff7f0e', height=bar_height, label='Q2')
  18. bars3 = ax.barh(r3, q3_values, color='#2ca02c', height=bar_height, label='Q3')
  19. bars4 = ax.barh(r4, q4_values, color='#d62728', height=bar_height, label='Q4')
  20. # 添加数据标签
  21. def add_h_labels(bars):
  22.     for bar in bars:
  23.         width = bar.get_width()
  24.         ax.text(width + 0.5, bar.get_y() + bar.get_height()/2.,
  25.                 f'{width}',
  26.                 ha='left', va='center', fontsize=9)
  27. add_h_labels(bars1)
  28. add_h_labels(bars2)
  29. add_h_labels(bars3)
  30. add_h_labels(bars4)
  31. # 添加标题和标签
  32. ax.set_title('产品季度销售额对比', fontsize=16, pad=20, fontweight='bold')
  33. ax.set_xlabel('销售额(万元)', fontsize=12)
  34. ax.set_ylabel('产品名称', fontsize=12)
  35. # 设置Y轴刻度和标签
  36. ax.set_yticks([r + bar_height * 1.5 for r in range(len(categories))])
  37. ax.set_yticklabels(categories)
  38. # 添加图例
  39. ax.legend()
  40. # 添加网格线
  41. ax.grid(axis='x', linestyle='--', alpha=0.7)
  42. # 设置背景色
  43. ax.set_facecolor('#f8f9fa')
  44. # 显示图表
  45. plt.tight_layout()
  46. plt.show()
复制代码

实例演示

实例1:销售数据分析可视化

让我们通过一个完整的实例来展示从数据准备到最终美化的全过程。假设我们有一组公司销售数据,需要创建一个专业的条形图来展示各产品在不同地区的销售情况。
  1. # 1. 数据准备
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import matplotlib as mpl
  6. from matplotlib.ticker import FuncFormatter
  7. # 设置中文字体
  8. plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
  9. plt.rcParams['axes.unicode_minus'] = False
  10. # 创建销售数据
  11. data = {
  12.     '产品': ['产品A', '产品B', '产品C', '产品D', '产品E'],
  13.     '华北': [120, 150, 90, 180, 110],
  14.     '华东': [200, 180, 150, 220, 160],
  15.     '华南': [150, 170, 120, 190, 140],
  16.     '西部': [80, 100, 70, 110, 90]
  17. }
  18. df = pd.DataFrame(data)
  19. # 计算每个产品的总销售额
  20. df['总销售额'] = df[['华北', '华东', '华南', '西部']].sum(axis=1)
  21. # 按总销售额排序
  22. df = df.sort_values('总销售额', ascending=False)
  23. # 2. 创建图形和坐标轴
  24. fig, ax = plt.subplots(figsize=(14, 8))
  25. # 3. 绘制条形图
  26. bar_width = 0.2
  27. r1 = np.arange(len(df))
  28. r2 = [x + bar_width for x in r1]
  29. r3 = [x + bar_width for x in r2]
  30. r4 = [x + bar_width for x in r3]
  31. # 定义颜色
  32. colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
  33. # 绘制分组条形图
  34. bars1 = ax.bar(r1, df['华北'], color=colors[0], width=bar_width, edgecolor='white', label='华北')
  35. bars2 = ax.bar(r2, df['华东'], color=colors[1], width=bar_width, edgecolor='white', label='华东')
  36. bars3 = ax.bar(r3, df['华南'], color=colors[2], width=bar_width, edgecolor='white', label='华南')
  37. bars4 = ax.bar(r4, df['西部'], color=colors[3], width=bar_width, edgecolor='white', label='西部')
  38. # 4. 添加数据标签
  39. def add_labels(bars):
  40.     for bar in bars:
  41.         height = bar.get_height()
  42.         ax.text(bar.get_x() + bar.get_width()/2., height,
  43.                 f'{height}',
  44.                 ha='center', va='bottom', fontsize=9)
  45. add_labels(bars1)
  46. add_labels(bars2)
  47. add_labels(bars3)
  48. add_labels(bars4)
  49. # 5. 添加标题和标签
  50. ax.set_title('2023年各产品地区销售额对比', fontsize=18, pad=20, fontweight='bold')
  51. ax.set_xlabel('产品名称', fontsize=14)
  52. ax.set_ylabel('销售额(万元)', fontsize=14)
  53. # 6. 设置X轴刻度和标签
  54. ax.set_xticks([r + bar_width * 1.5 for r in range(len(df))])
  55. ax.set_xticklabels(df['产品'], fontsize=12)
  56. # 7. 添加图例
  57. ax.legend(fontsize=12, frameon=True, fancybox=True, shadow=True)
  58. # 8. 添加网格线
  59. ax.grid(axis='y', linestyle='--', alpha=0.7)
  60. # 9. 设置背景色
  61. ax.set_facecolor('#f8f9fa')
  62. # 10. 添加注释
  63. max_value = df[['华北', '华东', '华南', '西部']].max().max()
  64. max_product = df['产品'].iloc[df[['华北', '华东', '华南', '西部']].values.argmax() // 4]
  65. max_region = ['华北', '华东', '华南', '西部'][df[['华北', '华东', '华南', '西部']].values.argmax() % 4]
  66. ax.annotate(f'最高销售额: {max_value}万元\n{max_product} - {max_region}',
  67.             xy=(df[['华北', '华东', '华南', '西部']].values.argmax() % 4 +
  68.                 (df[['华北', '华东', '华南', '西部']].values.argmax() // 4) * bar_width * 4,
  69.                 max_value),
  70.             xytext=(df[['华北', '华东', '华南', '西部']].values.argmax() % 4 +
  71.                    (df[['华北', '华东', '华南', '西部']].values.argmax() // 4) * bar_width * 4,
  72.                    max_value + 30),
  73.             arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8),
  74.             ha='center', fontsize=10, bbox=dict(boxstyle="round,pad=0.3", fc="yellow", ec="black", lw=0.5))
  75. # 11. 添加数据来源注释
  76. fig.text(0.5, 0.01, '数据来源: 公司销售部门 2023年度报告',
  77.          ha='center', fontsize=10, color='gray')
  78. # 12. 调整布局
  79. plt.tight_layout(rect=[0, 0.03, 1, 0.97])
  80. # 13. 保存图表
  81. plt.savefig('sales_comparison.png', dpi=300, bbox_inches='tight')
  82. # 14. 显示图表
  83. plt.show()
复制代码

实例2:客户满意度调查结果可视化

在这个实例中,我们将创建一个水平条形图来展示客户满意度调查结果,包括使用渐变色彩和添加数据标签。
  1. # 1. 数据准备
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib.colors import LinearSegmentedColormap
  5. import pandas as pd
  6. # 设置中文字体
  7. plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
  8. plt.rcParams['axes.unicode_minus'] = False
  9. # 创建客户满意度数据
  10. data = {
  11.     '服务项目': ['产品质量', '售后服务', '配送速度', '价格合理性', '网站体验', '客户沟通'],
  12.     '满意度': [4.5, 3.8, 4.2, 3.5, 4.0, 3.9],
  13.     '去年满意度': [4.2, 3.5, 3.9, 3.3, 3.8, 3.7]
  14. }
  15. df = pd.DataFrame(data)
  16. # 计算变化值
  17. df['变化'] = df['满意度'] - df['去年满意度']
  18. # 按当前满意度排序
  19. df = df.sort_values('满意度', ascending=True)
  20. # 2. 创建图形和坐标轴
  21. fig, ax = plt.subplots(figsize=(12, 8))
  22. # 3. 创建渐变色映射
  23. cmap = LinearSegmentedColormap.from_list('satisfaction', ['#d62728', '#ff7f0e', '#2ca02c'], N=100)
  24. # 4. 绘制水平条形图
  25. bars = ax.barh(df['服务项目'], df['满意度'],
  26.                color=[cmap((x-1)/4) for x in df['满意度']],
  27.                edgecolor='white', linewidth=1.2)
  28. # 5. 添加去年满意度数据点
  29. ax.scatter(df['去年满意度'], np.arange(len(df)), color='gray', s=50, label='去年满意度', zorder=5)
  30. # 6. 连接去年和今年的数据点
  31. for i, (current, last) in enumerate(zip(df['满意度'], df['去年满意度'])):
  32.     ax.plot([last, current], [i, i], 'gray', linestyle='--', alpha=0.5, linewidth=1)
  33. # 7. 添加数据标签
  34. for i, (bar, value, change) in enumerate(zip(bars, df['满意度'], df['变化'])):
  35.     # 当前满意度标签
  36.     ax.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2.,
  37.             f'{value:.1f}',
  38.             ha='left', va='center', fontsize=11, fontweight='bold')
  39.    
  40.     # 变化值标签
  41.     if change > 0:
  42.         ax.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height()/2.,
  43.                 f'+{change:.1f}',
  44.                 ha='left', va='center', fontsize=10, color='green', fontweight='bold')
  45.     elif change < 0:
  46.         ax.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height()/2.,
  47.                 f'{change:.1f}',
  48.                 ha='left', va='center', fontsize=10, color='red', fontweight='bold')
  49. # 8. 添加标题和标签
  50. ax.set_title('客户满意度调查结果', fontsize=18, pad=20, fontweight='bold')
  51. ax.set_xlabel('满意度评分 (1-5分)', fontsize=14)
  52. # 9. 设置X轴范围和刻度
  53. ax.set_xlim(0, 5.5)
  54. ax.set_xticks(np.arange(0, 5.1, 0.5))
  55. # 10. 添加网格线
  56. ax.grid(axis='x', linestyle='--', alpha=0.7)
  57. # 11. 设置背景色
  58. ax.set_facecolor('#f8f9fa')
  59. # 12. 添加图例
  60. ax.legend(loc='lower right', fontsize=12, frameon=True, fancybox=True, shadow=True)
  61. # 13. 添加评分说明
  62. fig.text(0.5, 0.01, '评分说明: 1分=非常不满意, 2分=不满意, 3分=一般, 4分=满意, 5分=非常满意',
  63.          ha='center', fontsize=10, color='gray')
  64. # 14. 添加颜色条说明
  65. sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=1, vmax=5))
  66. sm.set_array([])
  67. cbar = plt.colorbar(sm, ax=ax, orientation='vertical', pad=0.01)
  68. cbar.set_label('满意度等级', fontsize=12)
  69. # 15. 调整布局
  70. plt.tight_layout(rect=[0, 0.03, 0.95, 0.97])
  71. # 16. 保存图表
  72. plt.savefig('customer_satisfaction.png', dpi=300, bbox_inches='tight')
  73. # 17. 显示图表
  74. plt.show()
复制代码

总结与建议

通过本文的介绍,我们详细学习了如何使用Matplotlib在Python中创建专业的条形图,包括数据准备、基础条形图创建、图表定制和美化技巧,以及各种高级条形图类型的实现。以下是一些总结和建议:

最佳实践

1. 数据准备是关键:在创建图表之前,确保数据已经过适当的清洗、排序和格式化。使用Pandas可以大大简化数据处理的步骤。
2. 选择合适的图表类型:根据数据的特点和分析目的,选择最合适的条形图类型。例如,比较多个类别的数值时使用分组条形图,展示部分与整体的关系时使用堆叠条形图。
3. 注重可读性:确保图表中的文字清晰可读,包括标题、标签和数据标签。调整字体大小、颜色和位置以提高可读性。
4. 使用专业配色:选择合适的颜色方案可以提高图表的视觉效果和专业性。可以使用Matplotlib内置的colormap或自定义颜色方案。
5. 添加必要的注释:通过添加标题、图例、数据来源等注释,使图表更加完整和易于理解。
6. 保持简洁:避免在图表中添加过多不必要的元素,保持图表简洁明了。

数据准备是关键:在创建图表之前,确保数据已经过适当的清洗、排序和格式化。使用Pandas可以大大简化数据处理的步骤。

选择合适的图表类型:根据数据的特点和分析目的,选择最合适的条形图类型。例如,比较多个类别的数值时使用分组条形图,展示部分与整体的关系时使用堆叠条形图。

注重可读性:确保图表中的文字清晰可读,包括标题、标签和数据标签。调整字体大小、颜色和位置以提高可读性。

使用专业配色:选择合适的颜色方案可以提高图表的视觉效果和专业性。可以使用Matplotlib内置的colormap或自定义颜色方案。

添加必要的注释:通过添加标题、图例、数据来源等注释,使图表更加完整和易于理解。

保持简洁:避免在图表中添加过多不必要的元素,保持图表简洁明了。

常见问题与解决方案

1. 中文显示问题:在Matplotlib中显示中文时,需要设置合适的中文字体,如SimHei或Arial Unicode MS。
2. 图表保存问题:保存图表时,使用bbox_inches='tight'参数可以防止标签被截断,使用dpi参数可以控制图像质量。
3. 图表布局问题:使用plt.tight_layout()可以自动调整图表布局,防止元素重叠。
4. 数据标签重叠问题:当数据标签较多时,可以通过调整标签位置、旋转角度或只显示部分标签来解决重叠问题。

中文显示问题:在Matplotlib中显示中文时,需要设置合适的中文字体,如SimHei或Arial Unicode MS。

图表保存问题:保存图表时,使用bbox_inches='tight'参数可以防止标签被截断,使用dpi参数可以控制图像质量。

图表布局问题:使用plt.tight_layout()可以自动调整图表布局,防止元素重叠。

数据标签重叠问题:当数据标签较多时,可以通过调整标签位置、旋转角度或只显示部分标签来解决重叠问题。

进阶技巧

1. 交互式图表:结合使用Matplotlib和mpld3库,可以创建交互式的条形图,支持鼠标悬停显示详细信息。
2. 动画效果:使用Matplotlib的动画功能,可以创建动态变化的条形图,展示数据随时间的变化。
3. 自定义样式:创建自定义的样式表,可以快速应用一致的设计风格到多个图表中。
4. 集成到Web应用:将Matplotlib图表集成到Web应用中,如使用Flask或Django框架创建数据可视化仪表板。

交互式图表:结合使用Matplotlib和mpld3库,可以创建交互式的条形图,支持鼠标悬停显示详细信息。

动画效果:使用Matplotlib的动画功能,可以创建动态变化的条形图,展示数据随时间的变化。

自定义样式:创建自定义的样式表,可以快速应用一致的设计风格到多个图表中。

集成到Web应用:将Matplotlib图表集成到Web应用中,如使用Flask或Django框架创建数据可视化仪表板。

通过掌握这些技巧和最佳实践,你可以使用Matplotlib创建出专业、美观且信息丰富的条形图,有效地展示和分析数据。希望本文的教程对你有所帮助!
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则

关闭

站长推荐上一条 /1 下一条

手机版|联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.

>