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

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

利用Python pandas库轻松实现数据可视化输出精美图片从基础图表到高级可视化技巧全面解析助你快速掌握数据分析结果展示

3万

主题

317

科技点

3万

积分

大区版主

木柜子打湿

积分
31893

财Doro三倍冰淇淋无人之境【一阶】立华奏小樱(小丑装)⑨的冰沙以外的星空【二阶】

发表于 2025-10-3 23:20:01 | 显示全部楼层 |阅读模式

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

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

x
引言

在当今数据驱动的时代,数据可视化已成为数据分析过程中不可或缺的一环。通过将复杂的数据转化为直观的图表,我们能够更快速地发现数据中的模式、趋势和异常。Python作为数据科学领域最受欢迎的编程语言之一,其pandas库不仅提供了强大的数据处理能力,还内置了便捷的数据可视化功能。本文将全面介绍如何利用pandas库实现从基础图表到高级可视化的各种技巧,帮助你快速掌握数据分析结果展示的方法。

pandas可视化基础

安装和设置

在开始使用pandas进行数据可视化之前,我们需要确保已安装必要的库。pandas的可视化功能实际上是基于Matplotlib构建的,因此我们通常需要同时安装pandas和Matplotlib。
  1. # 安装必要的库
  2. !pip install pandas matplotlib
  3. # 导入所需的库
  4. import pandas as pd
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. # 设置matplotlib显示中文
  8. plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
  9. plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
  10. # 让matplotlib在Jupyter Notebook中内嵌显示
  11. %matplotlib inline
复制代码

pandas内置的plot方法

pandas的Series和DataFrame对象都内置了plot方法,这是进行数据可视化的最简单方式。plot方法实际上是Matplotlib的一个简单封装,让我们能够快速创建各种类型的图表。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
  4. df_cumsum = df.cumsum()
  5. # 使用plot方法绘制线图
  6. df_cumsum.plot(figsize=(10, 6))
  7. plt.title('简单线图示例')
  8. plt.xlabel('X轴')
  9. plt.ylabel('Y轴')
  10. plt.grid(True)
  11. plt.show()
复制代码

基础图表类型

线图

线图是最常用的图表类型之一,特别适合展示数据随时间变化的趋势。
  1. # 创建时间序列数据
  2. dates = pd.date_range(start='20230101', periods=100)
  3. ts = pd.Series(np.random.randn(100).cumsum(), index=dates)
  4. # 绘制线图
  5. plt.figure(figsize=(12, 6))
  6. ts.plot(color='green', linewidth=2, linestyle='-', marker='o', markersize=4)
  7. plt.title('股票价格模拟走势', fontsize=16)
  8. plt.xlabel('日期', fontsize=12)
  9. plt.ylabel('价格', fontsize=12)
  10. plt.grid(True, linestyle='--', alpha=0.7)
  11. plt.fill_between(ts.index, ts, 0, where=ts>0, facecolor='g', alpha=0.3)
  12. plt.fill_between(ts.index, ts, 0, where=ts<0, facecolor='r', alpha=0.3)
  13. plt.show()
复制代码

柱状图

柱状图适合比较不同类别的数据值大小。
  1. # 创建示例数据
  2. categories = ['A类', 'B类', 'C类', 'D类', 'E类']
  3. values = np.random.randint(10, 100, size=5)
  4. df_bar = pd.DataFrame({'类别': categories, '数值': values})
  5. # 绘制柱状图
  6. plt.figure(figsize=(10, 6))
  7. df_bar.plot(x='类别', y='数值', kind='bar', color='skyblue', legend=False)
  8. plt.title('各类别数值比较', fontsize=16)
  9. plt.xlabel('类别', fontsize=12)
  10. plt.ylabel('数值', fontsize=12)
  11. plt.xticks(rotation=0)
  12. # 在柱子上方添加数值标签
  13. for i, v in enumerate(values):
  14.     plt.text(i, v + 1, str(v), ha='center')
  15.    
  16. plt.grid(axis='y', linestyle='--', alpha=0.7)
  17. plt.tight_layout()
  18. plt.show()
复制代码

堆叠柱状图

堆叠柱状图可以同时展示总体和各部分的比例关系。
  1. # 创建示例数据
  2. years = ['2018', '2019', '2020', '2021', '2022']
  3. product_A = np.random.randint(100, 200, size=5)
  4. product_B = np.random.randint(100, 200, size=5)
  5. product_C = np.random.randint(100, 200, size=5)
  6. df_stack = pd.DataFrame({
  7.     '年份': years,
  8.     '产品A': product_A,
  9.     '产品B': product_B,
  10.     '产品C': product_C
  11. }).set_index('年份')
  12. # 绘制堆叠柱状图
  13. plt.figure(figsize=(10, 6))
  14. df_stack.plot(kind='bar', stacked=True, figsize=(10, 6))
  15. plt.title('各产品年度销量堆叠图', fontsize=16)
  16. plt.xlabel('年份', fontsize=12)
  17. plt.ylabel('销量', fontsize=12)
  18. plt.xticks(rotation=0)
  19. plt.legend(title='产品类别')
  20. # 添加总数值标签
  21. for i, total in enumerate(df_stack.sum(axis=1)):
  22.     plt.text(i, total + 10, str(total), ha='center')
  23.    
  24. plt.grid(axis='y', linestyle='--', alpha=0.7)
  25. plt.tight_layout()
  26. plt.show()
复制代码

散点图

散点图适合展示两个变量之间的关系。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. N = 100
  4. x = np.random.rand(N)
  5. y = np.random.rand(N)
  6. colors = np.random.rand(N)
  7. sizes = 1000 * np.random.rand(N)
  8. df_scatter = pd.DataFrame({
  9.     'X值': x,
  10.     'Y值': y,
  11.     '颜色': colors,
  12.     '大小': sizes
  13. })
  14. # 绘制散点图
  15. plt.figure(figsize=(10, 8))
  16. scatter = plt.scatter(
  17.     df_scatter['X值'],
  18.     df_scatter['Y值'],
  19.     c=df_scatter['颜色'],
  20.     s=df_scatter['大小'],
  21.     alpha=0.6,
  22.     cmap='viridis'
  23. )
  24. plt.title('多维度散点图示例', fontsize=16)
  25. plt.xlabel('X值', fontsize=12)
  26. plt.ylabel('Y值', fontsize=12)
  27. plt.colorbar(scatter, label='颜色强度')
  28. plt.grid(True, linestyle='--', alpha=0.7)
  29. # 添加趋势线
  30. z = np.polyfit(df_scatter['X值'], df_scatter['Y值'], 1)
  31. p = np.poly1d(z)
  32. plt.plot(df_scatter['X值'], p(df_scatter['X值']), "r--", linewidth=2)
  33. plt.show()
复制代码

直方图

直方图适合展示数据的分布情况。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. data = pd.DataFrame({
  4.     '正态分布': np.random.normal(0, 1, 1000),
  5.     '指数分布': np.random.exponential(1, 1000),
  6.     '均匀分布': np.random.uniform(-1, 1, 1000)
  7. })
  8. # 绘制直方图
  9. plt.figure(figsize=(12, 8))
  10. data.plot(kind='hist', bins=30, alpha=0.5, figsize=(12, 8))
  11. plt.title('不同分布的直方图对比', fontsize=16)
  12. plt.xlabel('数值', fontsize=12)
  13. plt.ylabel('频数', fontsize=12)
  14. plt.grid(axis='y', linestyle='--', alpha=0.7)
  15. plt.legend()
  16. plt.show()
  17. # 分别绘制子图
  18. fig, axes = plt.subplots(1, 3, figsize=(18, 5))
  19. data['正态分布'].plot(kind='hist', bins=30, ax=axes[0], color='skyblue')
  20. axes[0].set_title('正态分布')
  21. data['指数分布'].plot(kind='hist', bins=30, ax=axes[1], color='salmon')
  22. axes[1].set_title('指数分布')
  23. data['均匀分布'].plot(kind='hist', bins=30, ax=axes[2], color='lightgreen')
  24. axes[2].set_title('均匀分布')
  25. for ax in axes:
  26.     ax.set_xlabel('数值')
  27.     ax.set_ylabel('频数')
  28.     ax.grid(axis='y', linestyle='--', alpha=0.7)
  29. plt.tight_layout()
  30. plt.show()
复制代码

箱线图

箱线图可以展示数据的中位数、四分位数和异常值,是进行数据分布比较的有效工具。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. data = pd.DataFrame({
  4.     'A组': np.random.normal(0, 1, 100),
  5.     'B组': np.random.normal(1, 1.5, 100),
  6.     'C组': np.random.normal(-1, 0.5, 100)
  7. })
  8. # 绘制箱线图
  9. plt.figure(figsize=(10, 6))
  10. data.plot(kind='box', figsize=(10, 6))
  11. plt.title('各组数据分布箱线图', fontsize=16)
  12. plt.ylabel('数值', fontsize=12)
  13. plt.grid(axis='y', linestyle='--', alpha=0.7)
  14. plt.show()
  15. # 添加小提琴图
  16. plt.figure(figsize=(10, 6))
  17. data.plot(kind='box', vert=False, positions=[1, 2, 3], widths=0.6)
  18. plt.yticks([1, 2, 3], ['A组', 'B组', 'C组'])
  19. plt.title('水平箱线图', fontsize=16)
  20. plt.xlabel('数值', fontsize=12)
  21. plt.grid(axis='x', linestyle='--', alpha=0.7)
  22. plt.show()
复制代码

自定义图表样式和美化技巧

颜色和样式设置

通过自定义颜色和样式,我们可以使图表更加美观和专业。
  1. # 创建示例数据
  2. dates = pd.date_range(start='20230101', periods=12)
  3. sales = pd.DataFrame({
  4.     '产品A': np.random.randint(100, 200, size=12),
  5.     '产品B': np.random.randint(100, 200, size=12),
  6.     '产品C': np.random.randint(100, 200, size=12)
  7. }, index=dates)
  8. # 设置样式
  9. plt.style.use('ggplot')  # 使用ggplot风格
  10. # 自定义颜色
  11. colors = ['#1f77b4', '#ff7f0e', '#2ca02c']
  12. # 绘制图表
  13. fig, ax = plt.subplots(figsize=(12, 6))
  14. sales.plot(ax=ax, color=colors, linewidth=2.5)
  15. # 添加标题和标签
  16. ax.set_title('2023年产品销售趋势', fontsize=16, pad=20)
  17. ax.set_xlabel('月份', fontsize=12)
  18. ax.set_ylabel('销售额', fontsize=12)
  19. # 自定义图例
  20. ax.legend(['产品A', '产品B', '产品C'], title='产品类别',
  21.           frameon=True, fancybox=True, shadow=True)
  22. # 添加网格
  23. ax.grid(True, linestyle='--', alpha=0.7)
  24. # 添加数据标签
  25. for col in sales.columns:
  26.     for i, value in enumerate(sales[col]):
  27.         ax.annotate(f'{value}',
  28.                    xy=(i, value),
  29.                    xytext=(0, 5),
  30.                    textcoords='offset points',
  31.                    ha='center',
  32.                    va='bottom',
  33.                    fontsize=8)
  34. # 调整x轴刻度
  35. ax.set_xticks(range(len(sales.index)))
  36. ax.set_xticklabels([d.strftime('%m月') for d in sales.index])
  37. plt.tight_layout()
  38. plt.show()
复制代码

添加注释和标记

在图表中添加注释和标记可以帮助读者更好地理解数据的关键点。
  1. # 创建示例数据
  2. dates = pd.date_range(start='20230101', periods=24)
  3. values = pd.Series(np.random.randn(24).cumsum(), index=dates)
  4. # 找出最大值和最小值
  5. max_date = values.idxmax()
  6. max_value = values.max()
  7. min_date = values.idxmin()
  8. min_value = values.min()
  9. # 绘制图表
  10. plt.figure(figsize=(14, 7))
  11. values.plot(color='royalblue', linewidth=2.5, label='数值')
  12. # 标记最大值和最小值
  13. plt.scatter(max_date, max_value, color='red', s=100, zorder=5)
  14. plt.scatter(min_date, min_value, color='green', s=100, zorder=5)
  15. # 添加注释
  16. plt.annotate(f'最大值: {max_value:.2f}',
  17.              xy=(max_date, max_value),
  18.              xytext=(max_date, max_value + 2),
  19.              arrowprops=dict(facecolor='red', shrink=0.05, width=1, headwidth=8),
  20.              ha='center', fontsize=12)
  21. plt.annotate(f'最小值: {min_value:.2f}',
  22.              xy=(min_date, min_value),
  23.              xytext=(min_date, min_value - 2),
  24.              arrowprops=dict(facecolor='green', shrink=0.05, width=1, headwidth=8),
  25.              ha='center', fontsize=12)
  26. # 添加标题和标签
  27. plt.title('2023年数据趋势分析', fontsize=16, pad=20)
  28. plt.xlabel('日期', fontsize=12)
  29. plt.ylabel('数值', fontsize=12)
  30. plt.grid(True, linestyle='--', alpha=0.7)
  31. plt.legend()
  32. # 添加水平参考线
  33. plt.axhline(y=0, color='gray', linestyle='-', alpha=0.3)
  34. plt.tight_layout()
  35. plt.show()
复制代码

双轴图表

当需要同时展示两个不同量级或单位的数据时,双轴图表非常有用。
  1. # 创建示例数据
  2. dates = pd.date_range(start='20230101', periods=12)
  3. sales = pd.DataFrame({
  4.     '销售额': np.random.randint(100, 200, size=12),
  5.     '利润率': np.random.uniform(0.1, 0.3, size=12)
  6. }, index=dates)
  7. # 绘制双轴图表
  8. fig, ax1 = plt.subplots(figsize=(12, 6))
  9. # 绘制柱状图(销售额)
  10. color = 'tab:blue'
  11. ax1.set_xlabel('月份', fontsize=12)
  12. ax1.set_ylabel('销售额(万元)', color=color, fontsize=12)
  13. sales['销售额'].plot(kind='bar', ax=ax1, color=color, alpha=0.7, width=0.6)
  14. ax1.tick_params(axis='y', labelcolor=color)
  15. ax1.set_xticklabels([d.strftime('%m月') for d in sales.index], rotation=0)
  16. ax1.grid(axis='y', linestyle='--', alpha=0.7)
  17. # 创建第二个y轴
  18. ax2 = ax1.twinx()
  19. color = 'tab:red'
  20. ax2.set_ylabel('利润率', color=color, fontsize=12)
  21. sales['利润率'].plot(ax=ax2, color=color, marker='o', linewidth=2.5, markersize=8)
  22. ax2.tick_params(axis='y', labelcolor=color)
  23. ax2.set_ylim(0, 0.4)
  24. # 添加数据标签
  25. for i, v in enumerate(sales['销售额']):
  26.     ax1.text(i, v + 5, f'{v}', ha='center', fontsize=9)
  27. for i, v in enumerate(sales['利润率']):
  28.     ax2.text(i, v + 0.01, f'{v:.2%}', ha='center', fontsize=9, color=color)
  29. # 添加标题
  30. plt.title('2023年销售额与利润率双轴分析', fontsize=16, pad=20)
  31. fig.tight_layout()
  32. plt.show()
复制代码

高级可视化技巧

多子图绘制

在一个图形中展示多个子图可以方便地进行数据对比和分析。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. dates = pd.date_range(start='20230101', periods=12)
  4. sales_data = pd.DataFrame({
  5.     '产品A': np.random.randint(100, 200, size=12),
  6.     '产品B': np.random.randint(100, 200, size=12),
  7.     '产品C': np.random.randint(100, 200, size=12)
  8. }, index=dates)
  9. # 创建2x2的子图布局
  10. fig, axes = plt.subplots(2, 2, figsize=(15, 12))
  11. fig.suptitle('2023年产品销售数据分析', fontsize=20, y=1.02)
  12. # 子图1: 各产品月度销售趋势
  13. sales_data.plot(ax=axes[0, 0], linewidth=2.5)
  14. axes[0, 0].set_title('各产品月度销售趋势', fontsize=14)
  15. axes[0, 0].set_xlabel('月份')
  16. axes[0, 0].set_ylabel('销售额')
  17. axes[0, 0].grid(True, linestyle='--', alpha=0.7)
  18. axes[0, 0].legend()
  19. # 子图2: 月度总销售额柱状图
  20. monthly_total = sales_data.sum(axis=1)
  21. monthly_total.plot(kind='bar', ax=axes[0, 1], color='skyblue')
  22. axes[0, 1].set_title('月度总销售额', fontsize=14)
  23. axes[0, 1].set_xlabel('月份')
  24. axes[0, 1].set_ylabel('总销售额')
  25. axes[0, 1].set_xticklabels([d.strftime('%m月') for d in dates], rotation=0)
  26. axes[0, 1].grid(axis='y', linestyle='--', alpha=0.7)
  27. # 添加数据标签
  28. for i, v in enumerate(monthly_total):
  29.     axes[0, 1].text(i, v + 10, f'{v}', ha='center')
  30. # 子图3: 产品销售占比饼图
  31. product_total = sales_data.sum()
  32. product_total.plot(kind='pie', ax=axes[1, 0], autopct='%1.1f%%',
  33.                   startangle=90, colors=['#1f77b4', '#ff7f0e', '#2ca02c'])
  34. axes[1, 0].set_title('产品销售占比', fontsize=14)
  35. axes[1, 0].set_ylabel('')
  36. # 子图4: 产品销售额箱线图
  37. sales_data.plot(kind='box', ax=axes[1, 1])
  38. axes[1, 1].set_title('产品销售额分布', fontsize=14)
  39. axes[1, 1].set_ylabel('销售额')
  40. axes[1, 1].grid(axis='y', linestyle='--', alpha=0.7)
  41. plt.tight_layout()
  42. plt.show()
复制代码

多变量数据可视化

当数据包含多个变量时,我们可以使用更复杂的可视化方法来展示变量之间的关系。
  1. # 创建示例数据
  2. np.random.seed(42)
  3. n_samples = 200
  4. data = pd.DataFrame({
  5.     '变量A': np.random.normal(0, 1, n_samples),
  6.     '变量B': np.random.normal(2, 1.5, n_samples),
  7.     '变量C': np.random.normal(-1, 0.8, n_samples),
  8.     '变量D': np.random.normal(1, 1.2, n_samples),
  9.     '类别': np.random.choice(['类别1', '类别2', '类别3'], size=n_samples)
  10. })
  11. # 创建相关性矩阵图
  12. corr_matrix = data.iloc[:, :4].corr()
  13. plt.figure(figsize=(10, 8))
  14. plt.imshow(corr_matrix, cmap='coolwarm', vmin=-1, vmax=1)
  15. plt.colorbar(label='相关系数')
  16. plt.title('变量相关性矩阵', fontsize=16)
  17. # 添加相关系数标签
  18. for i in range(len(corr_matrix)):
  19.     for j in range(len(corr_matrix)):
  20.         plt.text(j, i, f'{corr_matrix.iloc[i, j]:.2f}',
  21.                 ha='center', va='center', color='white' if abs(corr_matrix.iloc[i, j]) > 0.5 else 'black')
  22. plt.xticks(range(len(corr_matrix)), corr_matrix.columns)
  23. plt.yticks(range(len(corr_matrix)), corr_matrix.columns)
  24. plt.tight_layout()
  25. plt.show()
  26. # 创建散点图矩阵
  27. pd.plotting.scatter_matrix(data.iloc[:, :4], figsize=(12, 10), alpha=0.6,
  28.                           diagonal='kde', marker='o', grid=True)
  29. plt.suptitle('多变量散点图矩阵', fontsize=16, y=1.02)
  30. plt.tight_layout()
  31. plt.show()
  32. # 创建平行坐标图
  33. from pandas.plotting import parallel_coordinates
  34. plt.figure(figsize=(12, 6))
  35. parallel_coordinates(data, '类别', colormap='viridis')
  36. plt.title('多变量平行坐标图', fontsize=16)
  37. plt.xlabel('变量')
  38. plt.ylabel('数值')
  39. plt.grid(True, linestyle='--', alpha=0.7)
  40. plt.legend(title='类别')
  41. plt.tight_layout()
  42. plt.show()
复制代码

时间序列数据可视化

时间序列数据有其特殊的可视化需求,pandas提供了专门的功能来处理这类数据。
  1. # 创建时间序列数据
  2. np.random.seed(42)
  3. dates = pd.date_range(start='20220101', end='20221231', freq='D')
  4. sales = pd.DataFrame({
  5.     '销售额': np.random.randint(50, 200, size=len(dates)) +
  6.               np.sin(np.arange(len(dates)) * 2 * np.pi / 365.25) * 50 + 100
  7. }, index=dates)
  8. # 按月重采样
  9. monthly_sales = sales.resample('M').sum()
  10. # 按季度重采样
  11. quarterly_sales = sales.resample('Q').sum()
  12. # 计算滚动平均
  13. rolling_avg = sales.rolling(window=30).mean()
  14. # 绘制时间序列图
  15. plt.figure(figsize=(14, 8))
  16. sales['销售额'].plot(alpha=0.5, label='日销售额')
  17. rolling_avg['销售额'].plot(linewidth=2, label='30天滚动平均')
  18. monthly_sales['销售额'].plot(marker='o', linewidth=2, label='月销售额')
  19. quarterly_sales['销售额'].plot(marker='s', linewidth=3, label='季度销售额')
  20. plt.title('2022年销售数据分析', fontsize=16)
  21. plt.xlabel('日期', fontsize=12)
  22. plt.ylabel('销售额', fontsize=12)
  23. plt.grid(True, linestyle='--', alpha=0.7)
  24. plt.legend()
  25. plt.tight_layout()
  26. plt.show()
  27. # 季节性分解
  28. from statsmodels.tsa.seasonal import seasonal_decompose
  29. # 确保数据频率一致
  30. sales_freq = sales.asfreq('D')
  31. # 执行季节性分解
  32. result = seasonal_decompose(sales_freq['销售额'], model='additive', period=30)
  33. # 绘制分解结果
  34. fig, axes = plt.subplots(4, 1, figsize=(14, 12), sharex=True)
  35. result.observed.plot(ax=axes[0], legend=False)
  36. axes[0].set_title('原始数据', fontsize=14)
  37. axes[0].grid(True, linestyle='--', alpha=0.7)
  38. result.trend.plot(ax=axes[1], legend=False)
  39. axes[1].set_title('趋势', fontsize=14)
  40. axes[1].grid(True, linestyle='--', alpha=0.7)
  41. result.seasonal.plot(ax=axes[2], legend=False)
  42. axes[2].set_title('季节性', fontsize=14)
  43. axes[2].grid(True, linestyle='--', alpha=0.7)
  44. result.resid.plot(ax=axes[3], legend=False)
  45. axes[3].set_title('残差', fontsize=14)
  46. axes[3].grid(True, linestyle='--', alpha=0.7)
  47. plt.suptitle('时间序列季节性分解', fontsize=16, y=1.02)
  48. plt.tight_layout()
  49. plt.show()
复制代码

地理数据可视化

地理数据可视化可以帮助我们理解数据在空间上的分布和关系。
  1. # 安装和导入地理可视化库
  2. !pip install geopandas folium
  3. import geopandas as gpd
  4. import folium
  5. from folium.plugins import HeatMap
  6. # 创建示例地理数据
  7. np.random.seed(42)
  8. cities = ['北京', '上海', '广州', '深圳', '成都', '杭州', '武汉', '西安']
  9. lats = [39.9042, 31.2304, 23.1291, 22.5431, 30.5728, 30.2741, 30.5928, 34.3416]
  10. lons = [116.4074, 121.4737, 113.2644, 114.0579, 104.0668, 120.1551, 114.3055, 108.9398]
  11. values = np.random.randint(50, 200, size=8)
  12. geo_data = pd.DataFrame({
  13.     '城市': cities,
  14.     '纬度': lats,
  15.     '经度': lons,
  16.     '数值': values
  17. })
  18. # 创建基础地图
  19. m = folium.Map(location=[35, 110], zoom_start=5)
  20. # 添加标记点
  21. for i, row in geo_data.iterrows():
  22.     folium.CircleMarker(
  23.         location=[row['纬度'], row['经度']],
  24.         radius=row['数值'] / 10,
  25.         popup=f"{row['城市']}: {row['数值']}",
  26.         color='crimson',
  27.         fill=True,
  28.         fill_color='crimson'
  29.     ).add_to(m)
  30. # 显示地图
  31. m
  32. # 创建热力图
  33. heat_data = [[row['纬度'], row['经度'], row['数值']] for i, row in geo_data.iterrows()]
  34. m_heat = folium.Map(location=[35, 110], zoom_start=5)
  35. HeatMap(heat_data).add_to(m_heat)
  36. # 显示热力图
  37. m_heat
复制代码

pandas与其他可视化库的结合

虽然pandas内置的可视化功能已经相当强大,但与其他专业可视化库结合使用可以实现更丰富的效果。

与Seaborn结合

Seaborn是基于Matplotlib的高级可视化库,提供了更美观的统计图表。
  1. # 安装seaborn
  2. !pip install seaborn
  3. import seaborn as sns
  4. # 创建示例数据
  5. np.random.seed(42)
  6. data = pd.DataFrame({
  7.     '类别': np.random.choice(['A', 'B', 'C', 'D'], size=200),
  8.     '数值1': np.random.normal(0, 1, size=200),
  9.     '数值2': np.random.normal(1, 1.5, size=200),
  10.     '分组': np.random.choice(['组1', '组2'], size=200)
  11. })
  12. # 设置Seaborn风格
  13. sns.set(style="whitegrid")
  14. plt.figure(figsize=(12, 6))
  15. # 绘制小提琴图
  16. sns.violinplot(x='类别', y='数值1', hue='分组', data=data, split=True)
  17. plt.title('不同类别和分组的数值分布', fontsize=16)
  18. plt.xlabel('类别', fontsize=12)
  19. plt.ylabel('数值', fontsize=12)
  20. plt.legend(title='分组')
  21. plt.tight_layout()
  22. plt.show()
  23. # 绘制成对关系图
  24. plt.figure(figsize=(10, 8))
  25. sns.pairplot(data, hue='类别', vars=['数值1', '数值2'], palette='viridis')
  26. plt.suptitle('多变量成对关系', y=1.02)
  27. plt.tight_layout()
  28. plt.show()
  29. # 绘制联合分布图
  30. plt.figure(figsize=(10, 8))
  31. sns.jointplot(x='数值1', y='数值2', data=data, kind='reg', hue='类别')
  32. plt.suptitle('两变量联合分布与回归', y=1.02)
  33. plt.tight_layout()
  34. plt.show()
复制代码

与Plotly结合

Plotly是一个交互式可视化库,可以创建动态、可交互的图表。
  1. # 安装plotly
  2. !pip install plotly
  3. import plotly.express as px
  4. import plotly.graph_objects as go
  5. from plotly.subplots import make_subplots
  6. # 创建示例数据
  7. dates = pd.date_range(start='20230101', periods=12)
  8. sales_data = pd.DataFrame({
  9.     '月份': dates,
  10.     '产品A': np.random.randint(100, 200, size=12),
  11.     '产品B': np.random.randint(100, 200, size=12),
  12.     '产品C': np.random.randint(100, 200, size=12)
  13. })
  14. # 转换为长格式
  15. sales_long = pd.melt(sales_data, id_vars=['月份'], var_name='产品', value_name='销售额')
  16. # 创建交互式线图
  17. fig = px.line(sales_long, x='月份', y='销售额', color='产品',
  18.               title='2023年产品销售趋势',
  19.               labels={'月份': '月份', '销售额': '销售额', '产品': '产品类别'},
  20.               line_shape='linear')
  21. # 添加自定义样式
  22. fig.update_layout(
  23.     title_font_size=20,
  24.     xaxis_title_font_size=14,
  25.     yaxis_title_font_size=14,
  26.     legend_title_font_size=14,
  27.     hovermode='x unified'
  28. )
  29. fig.show()
  30. # 创建交互式柱状图
  31. fig_bar = px.bar(sales_long, x='月份', y='销售额', color='产品',
  32.                 title='2023年产品销售柱状图',
  33.                 labels={'月份': '月份', '销售额': '销售额', '产品': '产品类别'},
  34.                 barmode='group')
  35. fig_bar.update_layout(
  36.     title_font_size=20,
  37.     xaxis_title_font_size=14,
  38.     yaxis_title_font_size=14,
  39.     legend_title_font_size=14
  40. )
  41. fig_bar.show()
  42. # 创建子图组合
  43. fig_sub = make_subplots(
  44.     rows=2, cols=2,
  45.     subplot_titles=('产品销售趋势', '产品销售占比', '月度总销售额', '产品销售额分布'),
  46.     specs=[[{"secondary_y": False}, {"type": "pie"}],
  47.            [{"secondary_y": False}, {"type": "box"}]]
  48. )
  49. # 添加线图
  50. for product in ['产品A', '产品B', '产品C']:
  51.     fig_sub.add_trace(
  52.         go.Scatter(x=sales_data['月份'], y=sales_data[product], name=product, mode='lines+markers'),
  53.         row=1, col=1
  54.     )
  55. # 添加饼图
  56. product_total = sales_data[['产品A', '产品B', '产品C']].sum()
  57. fig_sub.add_trace(
  58.     go.Pie(labels=product_total.index, values=product_total.values, name="销售占比"),
  59.     row=1, col=2
  60. )
  61. # 添加柱状图
  62. monthly_total = sales_data[['产品A', '产品B', '产品C']].sum(axis=1)
  63. fig_sub.add_trace(
  64.     go.Bar(x=sales_data['月份'], y=monthly_total, name='月度总销售额'),
  65.     row=2, col=1
  66. )
  67. # 添加箱线图
  68. for product in ['产品A', '产品B', '产品C']:
  69.     fig_sub.add_trace(
  70.         go.Box(y=sales_data[product], name=product),
  71.         row=2, col=2
  72.     )
  73. # 更新布局
  74. fig_sub.update_layout(
  75.     title_text="2023年产品销售数据综合分析",
  76.     title_font_size=20,
  77.     showlegend=False,
  78.     height=800
  79. )
  80. fig_sub.show()
复制代码

实际案例分析:从数据到可视化报告

让我们通过一个完整的案例,展示如何从原始数据到最终的可视化报告。
  1. # 步骤1: 数据准备
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import seaborn as sns
  6. # 创建模拟销售数据
  7. np.random.seed(42)
  8. dates = pd.date_range(start='20220101', end='20221231', freq='D')
  9. products = ['产品A', '产品B', '产品C', '产品D']
  10. regions = ['华北', '华东', '华南', '西南', '西北']
  11. # 生成基础数据
  12. data = []
  13. for date in dates:
  14.     for product in products:
  15.         for region in regions:
  16.             # 添加季节性因素
  17.             seasonal_factor = 1 + 0.3 * np.sin(2 * np.pi * (date.dayofyear - 80) / 365)
  18.             
  19.             # 添加产品基础销量
  20.             base_sales = {
  21.                 '产品A': 100,
  22.                 '产品B': 150,
  23.                 '产品C': 80,
  24.                 '产品D': 120
  25.             }[product]
  26.             
  27.             # 添加区域因子
  28.             region_factor = {
  29.                 '华北': 1.2,
  30.                 '华东': 1.5,
  31.                 '华南': 1.3,
  32.                 '西南': 0.9,
  33.                 '西北': 0.7
  34.             }[region]
  35.             
  36.             # 计算最终销量
  37.             sales = base_sales * seasonal_factor * region_factor * (0.8 + 0.4 * np.random.random())
  38.             
  39.             data.append({
  40.                 '日期': date,
  41.                 '产品': product,
  42.                 '区域': region,
  43.                 '销量': int(sales),
  44.                 '单价': np.random.randint(50, 200),
  45.                 '成本': np.random.randint(30, 150)
  46.             })
  47. # 创建DataFrame
  48. df = pd.DataFrame(data)
  49. # 计算销售额和利润
  50. df['销售额'] = df['销量'] * df['单价']
  51. df['利润'] = df['销售额'] - (df['销量'] * df['成本'])
  52. # 步骤2: 数据分析
  53. # 按月汇总数据
  54. df['月份'] = df['日期'].dt.to_period('M')
  55. monthly_data = df.groupby(['月份', '产品', '区域']).agg({
  56.     '销量': 'sum',
  57.     '销售额': 'sum',
  58.     '利润': 'sum'
  59. }).reset_index()
  60. # 步骤3: 创建可视化报告
  61. # 设置全局样式
  62. plt.style.use('seaborn')
  63. plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
  64. plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
  65. # 创建报告布局
  66. fig = plt.figure(figsize=(20, 25))
  67. fig.suptitle('2022年销售数据分析报告', fontsize=24, y=1.02)
  68. # 子图1: 月度总销售额趋势
  69. ax1 = plt.subplot(3, 2, 1)
  70. monthly_total = monthly_data.groupby('月份')['销售额'].sum()
  71. monthly_total.plot(ax=ax1, linewidth=3, marker='o', markersize=8, color='#1f77b4')
  72. ax1.set_title('月度总销售额趋势', fontsize=16)
  73. ax1.set_xlabel('月份', fontsize=12)
  74. ax1.set_ylabel('销售额(元)', fontsize=12)
  75. ax1.grid(True, linestyle='--', alpha=0.7)
  76. # 子图2: 产品销售额占比
  77. ax2 = plt.subplot(3, 2, 2)
  78. product_sales = monthly_data.groupby('产品')['销售额'].sum()
  79. product_sales.plot(kind='pie', ax=ax2, autopct='%1.1f%%', startangle=90,
  80.                   colors=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'])
  81. ax2.set_title('产品销售额占比', fontsize=16)
  82. ax2.set_ylabel('')
  83. # 子图3: 区域销售额对比
  84. ax3 = plt.subplot(3, 2, 3)
  85. region_sales = monthly_data.groupby('区域')['销售额'].sum().sort_values(ascending=False)
  86. region_sales.plot(kind='bar', ax=ax3, color='skyblue')
  87. ax3.set_title('区域销售额对比', fontsize=16)
  88. ax3.set_xlabel('区域', fontsize=12)
  89. ax3.set_ylabel('销售额(元)', fontsize=12)
  90. ax3.grid(axis='y', linestyle='--', alpha=0.7)
  91. # 添加数据标签
  92. for i, v in enumerate(region_sales):
  93.     ax3.text(i, v + region_sales.max() * 0.01, f'{v:,.0f}', ha='center')
  94. # 子图4: 产品月度销售趋势
  95. ax4 = plt.subplot(3, 2, 4)
  96. for product in products:
  97.     product_monthly = monthly_data[monthly_data['产品'] == product].groupby('月份')['销售额'].sum()
  98.     product_monthly.plot(ax=ax4, linewidth=2, label=product)
  99. ax4.set_title('产品月度销售趋势', fontsize=16)
  100. ax4.set_xlabel('月份', fontsize=12)
  101. ax4.set_ylabel('销售额(元)', fontsize=12)
  102. ax4.grid(True, linestyle='--', alpha=0.7)
  103. ax4.legend()
  104. # 子图5: 区域-产品热力图
  105. ax5 = plt.subplot(3, 2, 5)
  106. region_product = monthly_data.pivot_table(index='区域', columns='产品', values='销售额', aggfunc='sum')
  107. sns.heatmap(region_product, annot=True, fmt=',.0f', cmap='YlGnBu', ax=ax5)
  108. ax5.set_title('区域-产品销售额热力图', fontsize=16)
  109. ax5.set_xlabel('产品', fontsize=12)
  110. ax5.set_ylabel('区域', fontsize=12)
  111. # 子图6: 利润分析
  112. ax6 = plt.subplot(3, 2, 6)
  113. profit_data = monthly_data.groupby('月份').agg({
  114.     '销售额': 'sum',
  115.     '利润': 'sum'
  116. })
  117. profit_data['利润率'] = profit_data['利润'] / profit_data['销售额']
  118. # 创建双轴
  119. ax6_twin = ax6.twinx()
  120. # 绘制销售额柱状图
  121. profit_data['销售额'].plot(kind='bar', ax=ax6, color='skyblue', alpha=0.7, width=0.8)
  122. ax6.set_title('月度销售额与利润率分析', fontsize=16)
  123. ax6.set_xlabel('月份', fontsize=12)
  124. ax6.set_ylabel('销售额(元)', fontsize=12)
  125. ax6.set_xticklabels([str(m).split('-')[1] + '月' for m in profit_data.index], rotation=0)
  126. ax6.grid(axis='y', linestyle='--', alpha=0.7)
  127. # 绘制利润率线图
  128. profit_data['利润率'].plot(ax=ax6_twin, color='red', linewidth=3, marker='o', markersize=6)
  129. ax6_twin.set_ylabel('利润率', fontsize=12, color='red')
  130. ax6_twin.tick_params(axis='y', labelcolor='red')
  131. ax6_twin.set_ylim(0, 0.5)
  132. # 添加利润率标签
  133. for i, rate in enumerate(profit_data['利润率']):
  134.     ax6_twin.text(i, rate + 0.01, f'{rate:.1%}', ha='center', color='red')
  135. plt.tight_layout()
  136. plt.savefig('sales_analysis_report.png', dpi=300, bbox_inches='tight')
  137. plt.show()
  138. # 步骤4: 生成分析结论
  139. print("=== 2022年销售数据分析结论 ===")
  140. print(f"\n1. 年度总销售额: {monthly_data['销售额'].sum():,.0f}元")
  141. print(f"2. 年度总利润: {monthly_data['利润'].sum():,.0f}元")
  142. print(f"3. 年度平均利润率: {(monthly_data['利润'].sum() / monthly_data['销售额'].sum()):.1%}")
  143. print("\n4. 产品销售排名:")
  144. product_ranking = monthly_data.groupby('产品')['销售额'].sum().sort_values(ascending=False)
  145. for i, (product, sales) in enumerate(product_ranking.items(), 1):
  146.     print(f"   第{i}名: {product} - {sales:,.0f}元 ({sales/monthly_data['销售额'].sum():.1%})")
  147. print("\n5. 区域销售排名:")
  148. region_ranking = monthly_data.groupby('区域')['销售额'].sum().sort_values(ascending=False)
  149. for i, (region, sales) in enumerate(region_ranking.items(), 1):
  150.     print(f"   第{i}名: {region} - {sales:,.0f}元 ({sales/monthly_data['销售额'].sum():.1%})")
  151. print("\n6. 销售额最高月份:")
  152. best_month = monthly_data.groupby('月份')['销售额'].sum().idxmax()
  153. best_month_sales = monthly_data.groupby('月份')['销售额'].sum().max()
  154. print(f"   {best_month} - {best_month_sales:,.0f}元")
  155. print("\n7. 利润率分析:")
  156. profit_rate = monthly_data.groupby('月份').apply(lambda x: x['利润'].sum() / x['销售额'].sum())
  157. best_profit_month = profit_rate.idxmax()
  158. worst_profit_month = profit_rate.idxmin()
  159. print(f"   最高利润率月份: {best_profit_month} - {profit_rate.max():.1%}")
  160. print(f"   最低利润率月份: {worst_profit_month} - {profit_rate.min():.1%}")
复制代码

最佳实践和常见问题解决方案

最佳实践

1. 选择合适的图表类型时间序列数据:线图类别比较:柱状图分布情况:直方图、箱线图关系分析:散点图占比分析:饼图、堆叠柱状图
2. 时间序列数据:线图
3. 类别比较:柱状图
4. 分布情况:直方图、箱线图
5. 关系分析:散点图
6. 占比分析:饼图、堆叠柱状图
7. 保持图表简洁清晰避免过度装饰,专注于数据本身使用适当的颜色,确保对比度足够添加必要的标签和说明
8. 避免过度装饰,专注于数据本身
9. 使用适当的颜色,确保对比度足够
10. 添加必要的标签和说明
11. 注重数据准确性确保数据预处理正确检查异常值和缺失值验证计算结果
12. 确保数据预处理正确
13. 检查异常值和缺失值
14. 验证计算结果
15. 考虑受众需求根据受众调整技术细节的深度提供必要的背景信息和解释突出关键发现和结论
16. 根据受众调整技术细节的深度
17. 提供必要的背景信息和解释
18. 突出关键发现和结论

选择合适的图表类型

• 时间序列数据:线图
• 类别比较:柱状图
• 分布情况:直方图、箱线图
• 关系分析:散点图
• 占比分析:饼图、堆叠柱状图

保持图表简洁清晰

• 避免过度装饰,专注于数据本身
• 使用适当的颜色,确保对比度足够
• 添加必要的标签和说明

注重数据准确性

• 确保数据预处理正确
• 检查异常值和缺失值
• 验证计算结果

考虑受众需求

• 根据受众调整技术细节的深度
• 提供必要的背景信息和解释
• 突出关键发现和结论

常见问题及解决方案
  1. # 解决方案:设置中文字体
  2. plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
  3. plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
复制代码
  1. # 解决方案:调整布局和边距
  2. plt.tight_layout()  # 自动调整子图参数
  3. # 或者手动调整
  4. plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.3, hspace=0.5)
复制代码
  1. # 解决方案:自定义图例位置
  2. plt.legend(loc='best')  # 自动选择最佳位置
  3. # 或者指定位置
  4. plt.legend(loc='upper right', bbox_to_anchor=(1.15, 1))
复制代码
  1. # 解决方案:数据采样或聚合
  2. # 采样
  3. sampled_data = df.sample(frac=0.1)  # 随机采样10%的数据
  4. # 聚合
  5. aggregated_data = df.groupby('category').agg({'value': 'mean'})
复制代码
  1. # 解决方案:调整导出参数
  2. plt.savefig('chart.png', dpi=300, bbox_inches='tight', quality=95)
  3. # 导出为矢量图
  4. plt.savefig('chart.pdf', format='pdf', bbox_inches='tight')
复制代码

结论与展望

通过本文的全面介绍,我们深入了解了如何利用Python pandas库实现从基础图表到高级可视化的各种技巧。pandas作为一个强大的数据处理和分析工具,其内置的可视化功能为我们提供了快速探索数据的便捷途径。同时,结合Matplotlib、Seaborn、Plotly等专业可视化库,我们可以创建更加精美和专业的数据可视化作品。

数据可视化不仅是展示数据的手段,更是发现数据中隐藏模式和洞察的重要工具。随着数据量的不断增长和分析需求的日益复杂,数据可视化技术也在不断发展。未来,我们可以期待更多交互式、动态化和智能化的可视化工具的出现,这将使数据分析工作更加高效和直观。

掌握pandas数据可视化技能,将帮助你在数据分析、商业智能、科学研究等领域更好地展示你的发现和成果。希望本文能够成为你学习pandas数据可视化的有力参考,助你在数据之路上走得更远。
回复

使用道具 举报

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

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.