简体中文 繁體中文 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

Matplotlib绘图完全指南从基础操作到高级可视化技巧助你轻松掌握Python数据可视化的核心方法与实战应用适合数据分析师和科研人员的实用教程

3万

主题

424

科技点

3万

积分

大区版主

木柜子打湿

积分
31917

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

发表于 2025-10-5 11:20:00 | 显示全部楼层 |阅读模式 [标记阅至此楼]

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

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

x
引言

Matplotlib是Python中最流行的数据可视化库之一,它提供了强大而灵活的绘图功能,能够满足从简单到复杂的数据可视化需求。无论是数据分析、科学计算还是机器学习结果的展示,Matplotlib都是不可或缺的工具。本指南将带您从基础操作开始,逐步深入到高级可视化技巧,帮助您全面掌握Python数据可视化的核心方法与实战应用。

Matplotlib基础

安装与导入

在开始使用Matplotlib之前,首先需要确保已正确安装该库。可以通过pip或conda进行安装:
  1. # 使用pip安装
  2. pip install matplotlib
  3. # 使用conda安装
  4. conda install matplotlib
复制代码

安装完成后,在Python脚本或Jupyter Notebook中导入Matplotlib:
  1. # 导入matplotlib.pyplot模块,通常简写为plt
  2. import matplotlib.pyplot as plt
  3. # 在Jupyter Notebook中启用内联绘图
  4. %matplotlib inline
  5. # 导入numpy用于生成数据
  6. import numpy as np
复制代码

Matplotlib的基本概念

Matplotlib的核心概念包括Figure(画布)、Axes(坐标系)和Axis(坐标轴):

• Figure:整个图像窗口,是所有图表元素的容器。
• Axes:Figure中的绘图区域,一个Figure可以包含多个Axes。
• Axis:坐标系中的x轴和y轴,包括刻度、标签等。

下面是一个简单的例子,展示了这些基本概念:
  1. # 创建一个Figure和一个Axes
  2. fig, ax = plt.subplots()
  3. # 在Axes上绘制数据
  4. ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
  5. # 显示图形
  6. plt.show()
复制代码

基本绘图

线图

线图是最常用的图表类型之一,适合展示数据随时间或有序类别的变化趋势。
  1. # 生成数据
  2. x = np.linspace(0, 10, 100)
  3. y = np.sin(x)
  4. # 创建线图
  5. plt.figure(figsize=(10, 6))  # 设置图形大小
  6. plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')  # 蓝色实线,线宽为2
  7. # 添加标题和标签
  8. plt.title('正弦函数', fontsize=14)
  9. plt.xlabel('x', fontsize=12)
  10. plt.ylabel('sin(x)', fontsize=12)
  11. # 添加图例和网格
  12. plt.legend(fontsize=12)
  13. plt.grid(True)
  14. # 显示图形
  15. plt.show()
复制代码

散点图

散点图用于展示两个变量之间的关系,特别适合观察数据分布和相关性。
  1. # 生成随机数据
  2. np.random.seed(42)
  3. x = np.random.randn(100)
  4. y = 2 * x + np.random.randn(100) * 0.5
  5. # 创建散点图
  6. plt.figure(figsize=(10, 6))
  7. plt.scatter(x, y, c='r', alpha=0.6, s=50, label='数据点')
  8. # 添加标题和标签
  9. plt.title('散点图示例', fontsize=14)
  10. plt.xlabel('X轴', fontsize=12)
  11. plt.ylabel('Y轴', fontsize=12)
  12. # 添加图例
  13. plt.legend(fontsize=12)
  14. # 显示图形
  15. plt.show()
复制代码

柱状图

柱状图适合比较不同类别的数据,展示离散数据的大小。
  1. # 定义数据
  2. categories = ['A', 'B', 'C', 'D', 'E']
  3. values = [23, 45, 56, 78, 32]
  4. # 创建柱状图
  5. plt.figure(figsize=(10, 6))
  6. bars = plt.bar(categories, values, color=['blue', 'green', 'red', 'purple', 'orange'])
  7. # 在柱子上方添加数值标签
  8. for bar in bars:
  9.     height = bar.get_height()
  10.     plt.text(bar.get_x() + bar.get_width()/2., height,
  11.              f'{height}',
  12.              ha='center', va='bottom')
  13. # 添加标题和标签
  14. plt.title('柱状图示例', fontsize=14)
  15. plt.xlabel('类别', fontsize=12)
  16. plt.ylabel('数值', fontsize=12)
  17. # 显示图形
  18. plt.show()
复制代码

饼图

饼图适合展示各部分占整体的比例关系。
  1. # 定义数据
  2. labels = ['苹果', '香蕉', '橙子', '葡萄', '其他']
  3. sizes = [30, 25, 20, 15, 10]
  4. explode = (0, 0.1, 0, 0, 0)  # 突出显示第二块
  5. # 创建饼图
  6. plt.figure(figsize=(10, 8))
  7. plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
  8.         shadow=True, startangle=90)
  9. # 确保饼图是圆形
  10. plt.axis('equal')
  11. # 添加标题
  12. plt.title('水果销售比例', fontsize=14)
  13. # 显示图形
  14. plt.show()
复制代码

图表定制

标题、标签与图例

添加适当的标题、轴标签和图例可以使图表更加清晰易懂:
  1. # 生成数据
  2. x = np.linspace(0, 10, 100)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. # 创建图形
  6. plt.figure(figsize=(12, 6))
  7. # 绘制两条曲线
  8. plt.plot(x, y1, 'r-', linewidth=2, label='sin(x)')
  9. plt.plot(x, y2, 'b--', linewidth=2, label='cos(x)')
  10. # 添加标题和标签
  11. plt.title('三角函数比较', fontsize=16, pad=20)
  12. plt.xlabel('x轴', fontsize=14, labelpad=10)
  13. plt.ylabel('y轴', fontsize=14, labelpad=10)
  14. # 设置刻度标签大小
  15. plt.xticks(fontsize=12)
  16. plt.yticks(fontsize=12)
  17. # 添加图例
  18. plt.legend(fontsize=12, loc='upper right')
  19. # 添加网格
  20. plt.grid(True, linestyle='--', alpha=0.7)
  21. # 显示图形
  22. plt.show()
复制代码

颜色、线型与标记

Matplotlib提供了丰富的颜色、线型和标记选项,可以根据需求自定义:
  1. # 生成数据
  2. x = np.linspace(0, 10, 20)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. y3 = np.sin(x) + np.cos(x)
  6. # 创建图形
  7. plt.figure(figsize=(12, 6))
  8. # 使用不同的颜色、线型和标记
  9. plt.plot(x, y1, 'r-', linewidth=2, markersize=8, label='sin(x) - 红色实线')
  10. plt.plot(x, y2, 'g--', linewidth=2, markersize=8, label='cos(x) - 绿色虚线')
  11. plt.plot(x, y3, 'b:', linewidth=2, marker='o', markersize=8,
  12.          markerfacecolor='blue', markeredgecolor='black',
  13.          label='sin(x)+cos(x) - 蓝色点线')
  14. # 添加标题和图例
  15. plt.title('不同线型和标记示例', fontsize=14)
  16. plt.legend(fontsize=12)
  17. # 显示图形
  18. plt.show()
复制代码

文本与注释

在图表中添加文本和注释可以突出显示重要信息:
  1. # 生成数据
  2. x = np.linspace(0, 10, 100)
  3. y = np.sin(x)
  4. # 创建图形
  5. plt.figure(figsize=(12, 6))
  6. plt.plot(x, y, 'b-', linewidth=2)
  7. # 添加标题和标签
  8. plt.title('带注释的正弦函数', fontsize=14)
  9. plt.xlabel('x', fontsize=12)
  10. plt.ylabel('sin(x)', fontsize=12)
  11. # 添加文本注释
  12. plt.text(5, 0.5, '正弦波', fontsize=12,
  13.          bbox=dict(facecolor='yellow', alpha=0.5))
  14. # 添加箭头注释
  15. plt.annotate('最大值', xy=(np.pi/2, 1), xytext=(3, 0.5),
  16.              arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8),
  17.              fontsize=12)
  18. plt.annotate('最小值', xy=(3*np.pi/2, -1), xytext=(6, -0.5),
  19.              arrowprops=dict(facecolor='black', shrink=0.05, width=1, headwidth=8),
  20.              fontsize=12)
  21. # 显示图形
  22. plt.show()
复制代码

多子图绘制

创建多个子图

Matplotlib提供了多种方法来创建包含多个子图的图形:
  1. # 创建2行2列的子图
  2. fig, axs = plt.subplots(2, 2, figsize=(12, 10))
  3. # 生成数据
  4. x = np.linspace(0, 10, 100)
  5. # 第一个子图:正弦函数
  6. axs[0, 0].plot(x, np.sin(x), 'r-')
  7. axs[0, 0].set_title('正弦函数')
  8. axs[0, 0].set_xlabel('x')
  9. axs[0, 0].set_ylabel('sin(x)')
  10. axs[0, 0].grid(True)
  11. # 第二个子图:余弦函数
  12. axs[0, 1].plot(x, np.cos(x), 'g-')
  13. axs[0, 1].set_title('余弦函数')
  14. axs[0, 1].set_xlabel('x')
  15. axs[0, 1].set_ylabel('cos(x)')
  16. axs[0, 1].grid(True)
  17. # 第三个子图:正切函数
  18. axs[1, 0].plot(x, np.tan(x), 'b-')
  19. axs[1, 0].set_title('正切函数')
  20. axs[1, 0].set_xlabel('x')
  21. axs[1, 0].set_ylabel('tan(x)')
  22. axs[1, 0].set_ylim(-5, 5)  # 限制y轴范围
  23. axs[1, 0].grid(True)
  24. # 第四个子图:指数函数
  25. axs[1, 1].plot(x, np.exp(x/5), 'm-')
  26. axs[1, 1].set_title('指数函数')
  27. axs[1, 1].set_xlabel('x')
  28. axs[1, 1].set_ylabel('exp(x/5)')
  29. axs[1, 1].grid(True)
  30. # 调整子图间距
  31. plt.tight_layout()
  32. # 显示图形
  33. plt.show()
复制代码

不规则子图布局

有时需要创建不规则布局的子图,可以使用GridSpec实现:
  1. import matplotlib.gridspec as gridspec
  2. # 创建图形和GridSpec
  3. fig = plt.figure(figsize=(12, 8))
  4. gs = gridspec.GridSpec(3, 3)
  5. # 创建不规则子图
  6. ax1 = fig.add_subplot(gs[0, :])  # 第一行,占所有列
  7. ax2 = fig.add_subplot(gs[1, 0:2])  # 第二行,占前两列
  8. ax3 = fig.add_subplot(gs[1, 2])  # 第二行,占第三列
  9. ax4 = fig.add_subplot(gs[2, :])  # 第三行,占所有列
  10. # 生成数据
  11. x = np.linspace(0, 10, 100)
  12. # 第一个子图:正弦函数
  13. ax1.plot(x, np.sin(x), 'r-')
  14. ax1.set_title('正弦函数')
  15. ax1.grid(True)
  16. # 第二个子图:散点图
  17. np.random.seed(42)
  18. x_scatter = np.random.randn(50)
  19. y_scatter = np.random.randn(50)
  20. ax2.scatter(x_scatter, y_scatter, c='b', alpha=0.6)
  21. ax2.set_title('散点图')
  22. ax2.grid(True)
  23. # 第三个子图:柱状图
  24. categories = ['A', 'B', 'C']
  25. values = [10, 20, 15]
  26. ax3.bar(categories, values, color=['red', 'green', 'blue'])
  27. ax3.set_title('柱状图')
  28. # 第四个子图:余弦函数
  29. ax4.plot(x, np.cos(x), 'g-')
  30. ax4.set_title('余弦函数')
  31. ax4.grid(True)
  32. # 调整子图间距
  33. plt.tight_layout()
  34. # 显示图形
  35. plt.show()
复制代码

共享坐标轴

当多个子图需要共享相同的坐标轴时,可以使用sharex或sharey参数:
  1. # 创建2行1列的子图,共享x轴
  2. fig, axs = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
  3. # 生成数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. # 第一个子图:正弦函数
  8. axs[0].plot(x, y1, 'r-', linewidth=2)
  9. axs[0].set_title('正弦和余弦函数')
  10. axs[0].set_ylabel('sin(x)')
  11. axs[0].grid(True)
  12. # 第二个子图:余弦函数
  13. axs[1].plot(x, y2, 'b-', linewidth=2)
  14. axs[1].set_xlabel('x')
  15. axs[1].set_ylabel('cos(x)')
  16. axs[1].grid(True)
  17. # 调整子图间距
  18. plt.tight_layout()
  19. # 显示图形
  20. plt.show()
复制代码

高级可视化

3D绘图

Matplotlib支持3D绘图,可以创建立体图形:
  1. from mpl_toolkits.mplot3d import Axes3D
  2. # 创建3D图形
  3. fig = plt.figure(figsize=(12, 8))
  4. ax = fig.add_subplot(111, projection='3d')
  5. # 生成数据
  6. x = np.linspace(-5, 5, 100)
  7. y = np.linspace(-5, 5, 100)
  8. x, y = np.meshgrid(x, y)
  9. z = np.sin(np.sqrt(x**2 + y**2))
  10. # 绘制3D表面
  11. surf = ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none', alpha=0.8)
  12. # 添加颜色条
  13. fig.colorbar(surf, shrink=0.5, aspect=5)
  14. # 设置标题和标签
  15. ax.set_title('3D表面图: sin(sqrt(x^2 + y^2))', fontsize=14)
  16. ax.set_xlabel('X轴', fontsize=12)
  17. ax.set_ylabel('Y轴', fontsize=12)
  18. ax.set_zlabel('Z轴', fontsize=12)
  19. # 显示图形
  20. plt.show()
复制代码

等高线图

等高线图适合展示三维数据的二维投影:
  1. # 创建图形
  2. plt.figure(figsize=(12, 8))
  3. # 生成数据
  4. x = np.linspace(-3, 3, 100)
  5. y = np.linspace(-3, 3, 100)
  6. x, y = np.meshgrid(x, y)
  7. z = x**2 + y**2
  8. # 绘制等高线图
  9. contour = plt.contour(x, y, z, levels=20, colors='black')
  10. plt.clabel(contour, inline=True, fontsize=8)
  11. # 绘制填充等高线图
  12. plt.contourf(x, y, z, levels=20, cmap='viridis', alpha=0.7)
  13. # 添加颜色条
  14. plt.colorbar()
  15. # 设置标题和标签
  16. plt.title('等高线图: x^2 + y^2', fontsize=14)
  17. plt.xlabel('X轴', fontsize=12)
  18. plt.ylabel('Y轴', fontsize=12)
  19. # 显示图形
  20. plt.show()
复制代码

热图

热图适合展示矩阵数据或二维分布:
  1. # 创建图形
  2. plt.figure(figsize=(10, 8))
  3. # 生成随机数据
  4. data = np.random.randn(10, 10)
  5. # 绘制热图
  6. heatmap = plt.imshow(data, cmap='YlGnBu', interpolation='nearest')
  7. # 添加颜色条
  8. plt.colorbar(heatmap)
  9. # 设置标题和标签
  10. plt.title('热图示例', fontsize=14)
  11. plt.xlabel('X轴', fontsize=12)
  12. plt.ylabel('Y轴', fontsize=12)
  13. # 显示图形
  14. plt.show()
复制代码

极坐标图

极坐标图适合展示周期性或方向性数据:
  1. # 创建极坐标图
  2. fig = plt.figure(figsize=(10, 8))
  3. ax = fig.add_subplot(111, polar=True)
  4. # 生成数据
  5. theta = np.linspace(0, 2*np.pi, 100)
  6. r = np.sin(3*theta)
  7. # 绘制极坐标图
  8. ax.plot(theta, r, 'r-', linewidth=2)
  9. # 填充区域
  10. ax.fill(theta, r, 'r', alpha=0.3)
  11. # 设置标题
  12. ax.set_title('极坐标图: r = sin(3θ)', fontsize=14, pad=20)
  13. # 显示图形
  14. plt.show()
复制代码

统计图表

直方图

直方图适合展示数据的分布情况:
  1. # 生成随机数据
  2. np.random.seed(42)
  3. data = np.random.normal(0, 1, 1000)
  4. # 创建图形
  5. plt.figure(figsize=(12, 6))
  6. # 绘制直方图
  7. n, bins, patches = plt.hist(data, bins=30, density=True, alpha=0.7, color='g')
  8. # 添加正态分布曲线
  9. mu, sigma = 0, 1
  10. x = np.linspace(min(data), max(data), 100)
  11. y = 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(- (x - mu)**2 / (2 * sigma**2))
  12. plt.plot(x, y, 'r-', linewidth=2, label='正态分布曲线')
  13. # 添加标题和标签
  14. plt.title('直方图与正态分布', fontsize=14)
  15. plt.xlabel('数值', fontsize=12)
  16. plt.ylabel('密度', fontsize=12)
  17. # 添加图例和网格
  18. plt.legend(fontsize=12)
  19. plt.grid(True, linestyle='--', alpha=0.7)
  20. # 显示图形
  21. plt.show()
复制代码

箱线图

箱线图适合展示数据的分布、离群值等统计信息:
  1. # 生成随机数据
  2. np.random.seed(42)
  3. data1 = np.random.normal(0, 1, 100)
  4. data2 = np.random.normal(1, 2, 100)
  5. data3 = np.random.normal(-1, 1.5, 100)
  6. # 创建图形
  7. plt.figure(figsize=(10, 6))
  8. # 绘制箱线图
  9. box = plt.boxplot([data1, data2, data3], labels=['数据组1', '数据组2', '数据组3'],
  10.                  patch_artist=True, widths=0.5)
  11. # 设置箱线颜色
  12. colors = ['lightblue', 'lightgreen', 'lightpink']
  13. for patch, color in zip(box['boxes'], colors):
  14.     patch.set_facecolor(color)
  15. # 添加标题和标签
  16. plt.title('箱线图示例', fontsize=14)
  17. plt.xlabel('数据组', fontsize=12)
  18. plt.ylabel('数值', fontsize=12)
  19. # 添加网格
  20. plt.grid(True, linestyle='--', alpha=0.7)
  21. # 显示图形
  22. plt.show()
复制代码

误差棒图

误差棒图适合展示数据的不确定性或变异性:
  1. # 生成数据
  2. x = np.arange(0, 10, 1)
  3. y = np.sin(x)
  4. y_err = np.random.uniform(0.1, 0.3, 10)
  5. # 创建图形
  6. plt.figure(figsize=(10, 6))
  7. # 绘制误差棒图
  8. plt.errorbar(x, y, yerr=y_err, fmt='-o', color='blue',
  9.              ecolor='red', elinewidth=2, capsize=5, capthick=2,
  10.              label='带误差的数据点')
  11. # 添加标题和标签
  12. plt.title('误差棒图示例', fontsize=14)
  13. plt.xlabel('X轴', fontsize=12)
  14. plt.ylabel('Y轴', fontsize=12)
  15. # 添加图例和网格
  16. plt.legend(fontsize=12)
  17. plt.grid(True, linestyle='--', alpha=0.7)
  18. # 显示图形
  19. plt.show()
复制代码

面积图

面积图适合展示随时间变化的累积效应:
  1. # 生成数据
  2. x = np.linspace(0, 10, 100)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. y3 = np.sin(x) + np.cos(x)
  6. # 创建图形
  7. plt.figure(figsize=(12, 6))
  8. # 绘制堆叠面积图
  9. plt.stackplot(x, y1, y2, y3, labels=['sin(x)', 'cos(x)', 'sin(x)+cos(x)'],
  10.               colors=['blue', 'green', 'red'], alpha=0.5)
  11. # 添加标题和标签
  12. plt.title('堆叠面积图示例', fontsize=14)
  13. plt.xlabel('X轴', fontsize=12)
  14. plt.ylabel('Y轴', fontsize=12)
  15. # 添加图例和网格
  16. plt.legend(loc='upper left', fontsize=12)
  17. plt.grid(True, linestyle='--', alpha=0.7)
  18. # 显示图形
  19. plt.show()
复制代码

动画与交互

创建动画

Matplotlib支持创建简单的动画,适合展示数据随时间的变化:
  1. from matplotlib.animation import FuncAnimation
  2. from IPython.display import HTML, display
  3. # 创建图形和轴
  4. fig, ax = plt.subplots(figsize=(10, 6))
  5. ax.set_xlim(0, 2*np.pi)
  6. ax.set_ylim(-1.1, 1.1)
  7. ax.set_title('正弦波动画', fontsize=14)
  8. ax.set_xlabel('x', fontsize=12)
  9. ax.set_ylabel('sin(x)', fontsize=12)
  10. ax.grid(True)
  11. # 创建线条对象
  12. line, = ax.plot([], [], 'r-', linewidth=2)
  13. # 初始化函数
  14. def init():
  15.     line.set_data([], [])
  16.     return line,
  17. # 更新函数
  18. def update(frame):
  19.     x = np.linspace(0, 2*np.pi, 1000)
  20.     y = np.sin(x + frame/10.0)
  21.     line.set_data(x, y)
  22.     return line,
  23. # 创建动画
  24. ani = FuncAnimation(fig, update, frames=100, init_func=init,
  25.                     blit=True, interval=50)
  26. # 在Jupyter Notebook中显示动画
  27. # display(HTML(ani.to_jshtml()))
  28. # 保存动画为GIF(需要安装imagemagick或pillow)
  29. # ani.save('sine_wave.gif', writer='pillow', fps=20)
  30. # 显示静态图像
  31. plt.show()
复制代码

交互式图表

使用Matplotlib的交互功能可以创建响应用户操作的图表:
  1. # 创建交互式图形
  2. plt.figure(figsize=(10, 6))
  3. # 生成数据
  4. x = np.linspace(0, 10, 100)
  5. y = np.sin(x)
  6. # 绘制线条
  7. line, = plt.plot(x, y, 'r-', linewidth=2, picker=5)  # picker设置选择容差
  8. # 添加标题和标签
  9. plt.title('点击图表查看坐标', fontsize=14)
  10. plt.xlabel('X轴', fontsize=12)
  11. plt.ylabel('Y轴', fontsize=12)
  12. plt.grid(True)
  13. # 定义点击事件处理函数
  14. def on_click(event):
  15.     if event.inaxes != plt.gca():
  16.         return
  17.    
  18.     # 获取点击位置
  19.     x_click, y_click = event.xdata, event.ydata
  20.    
  21.     # 添加文本显示点击坐标
  22.     plt.gca().text(x_click, y_click, f'({x_click:.2f}, {y_click:.2f})',
  23.                   fontsize=10, bbox=dict(facecolor='yellow', alpha=0.7))
  24.    
  25.     # 重绘图形
  26.     plt.draw()
  27. # 定义拾取事件处理函数
  28. def on_pick(event):
  29.     thisline = event.artist
  30.     xdata = thisline.get_xdata()
  31.     ydata = thisline.get_ydata()
  32.     ind = event.ind
  33.     points = np.column_stack([xdata[ind], ydata[ind]])
  34.     print(f'选中的点: {points}')
  35. # 连接事件处理函数
  36. plt.gcf().canvas.mpl_connect('button_press_event', on_click)
  37. plt.gcf().canvas.mpl_connect('pick_event', on_pick)
  38. # 显示图形
  39. plt.show()
复制代码

实战案例

数据分析可视化

假设我们有一个销售数据集,需要分析不同产品在不同地区的销售情况:
  1. import pandas as pd
  2. # 创建示例数据
  3. np.random.seed(42)
  4. dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
  5. products = ['产品A', '产品B', '产品C', '产品D']
  6. regions = ['华北', '华东', '华南', '西部']
  7. # 生成随机销售数据
  8. data = []
  9. for date in dates:
  10.     for product in products:
  11.         for region in regions:
  12.             sales = np.random.randint(100, 1000)
  13.             data.append([date, product, region, sales])
  14. # 创建DataFrame
  15. df = pd.DataFrame(data, columns=['日期', '产品', '地区', '销售额'])
  16. # 按月份和产品汇总销售数据
  17. df['月份'] = df['日期'].dt.to_period('M')
  18. monthly_sales = df.groupby(['月份', '产品'])['销售额'].sum().reset_index()
  19. # 转换为宽格式
  20. monthly_sales_pivot = monthly_sales.pivot(index='月份', columns='产品', values='销售额')
  21. # 创建图形
  22. plt.figure(figsize=(14, 8))
  23. # 绘制多产品销售趋势
  24. for product in products:
  25.     plt.plot(monthly_sales_pivot.index.astype(str),
  26.              monthly_sales_pivot[product],
  27.              linewidth=2, label=product)
  28. # 添加标题和标签
  29. plt.title('2023年各产品月度销售额趋势', fontsize=16)
  30. plt.xlabel('月份', fontsize=14)
  31. plt.ylabel('销售额', fontsize=14)
  32. plt.xticks(rotation=45)
  33. # 添加图例和网格
  34. plt.legend(fontsize=12)
  35. plt.grid(True, linestyle='--', alpha=0.7)
  36. # 调整布局
  37. plt.tight_layout()
  38. # 显示图形
  39. plt.show()
复制代码

按地区分析销售额:
  1. # 按地区和产品汇总销售数据
  2. region_sales = df.groupby(['地区', '产品'])['销售额'].sum().reset_index()
  3. # 转换为宽格式
  4. region_sales_pivot = region_sales.pivot(index='地区', columns='产品', values='销售额')
  5. # 创建图形
  6. plt.figure(figsize=(12, 8))
  7. # 绘制堆叠柱状图
  8. bottom = np.zeros(len(regions))
  9. for i, product in enumerate(products):
  10.     plt.bar(regions, region_sales_pivot[product], bottom=bottom,
  11.             label=product, alpha=0.8)
  12.     bottom += region_sales_pivot[product]
  13. # 添加标题和标签
  14. plt.title('各地区产品销售额分布', fontsize=16)
  15. plt.xlabel('地区', fontsize=14)
  16. plt.ylabel('销售额', fontsize=14)
  17. # 添加图例
  18. plt.legend(fontsize=12)
  19. # 添加网格
  20. plt.grid(True, linestyle='--', alpha=0.7, axis='y')
  21. # 显示图形
  22. plt.show()
复制代码

科研数据可视化

假设我们有一组实验数据,需要可视化分析实验结果:
  1. # 模拟实验数据
  2. np.random.seed(42)
  3. control = np.random.normal(100, 10, 50)
  4. treatment1 = np.random.normal(120, 15, 50)
  5. treatment2 = np.random.normal(130, 12, 50)
  6. treatment3 = np.random.normal(140, 18, 50)
  7. # 创建图形
  8. fig, axs = plt.subplots(2, 2, figsize=(14, 10))
  9. # 第一个子图:箱线图比较
  10. axs[0, 0].boxplot([control, treatment1, treatment2, treatment3],
  11.                   labels=['对照组', '处理组1', '处理组2', '处理组3'],
  12.                   patch_artist=True)
  13. axs[0, 0].set_title('各组数据分布比较', fontsize=14)
  14. axs[0, 0].set_ylabel('测量值', fontsize=12)
  15. axs[0, 0].grid(True, linestyle='--', alpha=0.7)
  16. # 第二个子图:均值和标准误差
  17. means = [np.mean(control), np.mean(treatment1), np.mean(treatment2), np.mean(treatment3)]
  18. stds = [np.std(control), np.std(treatment1), np.std(treatment2), np.std(treatment3)]
  19. labels = ['对照组', '处理组1', '处理组2', '处理组3']
  20. axs[0, 1].bar(labels, means, yerr=stds, capsize=5, alpha=0.7,
  21.               color=['blue', 'green', 'red', 'purple'])
  22. axs[0, 1].set_title('各组均值与标准差', fontsize=14)
  23. axs[0, 1].set_ylabel('测量值', fontsize=12)
  24. axs[0, 1].grid(True, linestyle='--', alpha=0.7, axis='y')
  25. # 第三个子图:数据分布直方图
  26. axs[1, 0].hist(control, bins=15, alpha=0.5, label='对照组')
  27. axs[1, 0].hist(treatment1, bins=15, alpha=0.5, label='处理组1')
  28. axs[1, 0].hist(treatment2, bins=15, alpha=0.5, label='处理组2')
  29. axs[1, 0].hist(treatment3, bins=15, alpha=0.5, label='处理组3')
  30. axs[1, 0].set_title('数据分布直方图', fontsize=14)
  31. axs[1, 0].set_xlabel('测量值', fontsize=12)
  32. axs[1, 0].set_ylabel('频数', fontsize=12)
  33. axs[1, 0].legend(fontsize=10)
  34. axs[1, 0].grid(True, linestyle='--', alpha=0.7)
  35. # 第四个子图:散点图与拟合线
  36. x = np.arange(len(means))
  37. axs[1, 1].scatter(x, means, s=100, color='red')
  38. axs[1, 1].plot(x, means, 'r--', linewidth=2)
  39. # 添加误差棒
  40. axs[1, 1].errorbar(x, means, yerr=stds, fmt='none', ecolor='black',
  41.                    capsize=5, capthick=2)
  42. # 设置x轴刻度
  43. axs[1, 1].set_xticks(x)
  44. axs[1, 1].set_xticklabels(labels, rotation=45)
  45. axs[1, 1].set_title('各组均值趋势', fontsize=14)
  46. axs[1, 1].set_ylabel('测量值', fontsize=12)
  47. axs[1, 1].grid(True, linestyle='--', alpha=0.7)
  48. # 调整布局
  49. plt.tight_layout()
  50. # 显示图形
  51. plt.show()
复制代码

最佳实践与技巧

提高绘图效率

使用Matplotlib时,有一些技巧可以提高绘图效率:
  1. # 1. 使用面向对象的API,而不是pyplot接口
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
  4. ax.set_title('面向对象API示例')
  5. plt.show()
  6. # 2. 批量设置样式
  7. plt.style.use('seaborn')  # 使用预定义样式
  8. plt.rcParams['font.size'] = 12  # 设置全局字体大小
  9. plt.rcParams['axes.grid'] = True  # 默认显示网格
  10. fig, ax = plt.subplots(figsize=(10, 6))
  11. ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
  12. ax.set_title('批量设置样式示例')
  13. plt.show()
  14. # 3. 使用循环绘制多个相似图形
  15. fig, axs = plt.subplots(2, 2, figsize=(12, 10))
  16. colors = ['blue', 'green', 'red', 'purple']
  17. titles = ['图1', '图2', '图3', '图4']
  18. for i, ax in enumerate(axs.flat):
  19.     x = np.linspace(0, 10, 100)
  20.     y = np.sin(x) + i
  21.     ax.plot(x, y, color=colors[i])
  22.     ax.set_title(titles[i])
  23.     ax.grid(True)
  24. plt.tight_layout()
  25. plt.show()
  26. # 4. 使用上下文管理器临时设置参数
  27. with plt.rc_context({'figure.figsize': (10, 6), 'font.size': 14}):
  28.     plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
  29.     plt.title('上下文管理器设置参数示例')
  30.     plt.show()
复制代码

美化图表

美化图表可以提高其可读性和专业度:
  1. # 创建高质量图表
  2. fig, ax = plt.subplots(figsize=(12, 8), dpi=100)
  3. # 生成数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.sin(x) + np.cos(x)
  8. # 设置背景色
  9. fig.patch.set_facecolor('#f0f0f0')
  10. ax.set_facecolor('#ffffff')
  11. # 绘制曲线
  12. ax.plot(x, y1, linewidth=2, color='#1f77b4', label='sin(x)')
  13. ax.plot(x, y2, linewidth=2, color='#ff7f0e', label='cos(x)')
  14. ax.plot(x, y3, linewidth=2, color='#2ca02c', label='sin(x)+cos(x)')
  15. # 设置标题和标签
  16. ax.set_title('高质量图表示例', fontsize=16, pad=20, fontweight='bold')
  17. ax.set_xlabel('X轴', fontsize=14, labelpad=10)
  18. ax.set_ylabel('Y轴', fontsize=14, labelpad=10)
  19. # 设置刻度
  20. ax.tick_params(axis='both', which='major', labelsize=12, length=6, width=1.5)
  21. ax.tick_params(axis='both', which='minor', length=4, width=1)
  22. # 添加网格
  23. ax.grid(True, linestyle='--', alpha=0.7, linewidth=0.8)
  24. # 添加图例
  25. ax.legend(fontsize=12, framealpha=0.9, fancybox=True, shadow=True)
  26. # 添加边框
  27. for spine in ax.spines.values():
  28.     spine.set_edgecolor('#cccccc')
  29.     spine.set_linewidth(1.5)
  30. # 调整布局
  31. plt.tight_layout()
  32. # 保存高质量图片
  33. # plt.savefig('high_quality_plot.png', dpi=300, bbox_inches='tight')
  34. # 显示图形
  35. plt.show()
复制代码

导出高质量图片

Matplotlib支持多种格式的图片导出,可以根据需要选择合适的格式和参数:
  1. # 创建示例图形
  2. fig, ax = plt.subplots(figsize=(10, 6))
  3. x = np.linspace(0, 10, 100)
  4. y = np.sin(x)
  5. ax.plot(x, y, linewidth=2, color='blue')
  6. ax.set_title('示例图形')
  7. ax.set_xlabel('X轴')
  8. ax.set_ylabel('Y轴')
  9. ax.grid(True)
  10. # 导出为PNG格式(适合网页和演示)
  11. plt.savefig('plot.png', dpi=300, bbox_inches='tight', transparent=True)
  12. # 导出为PDF格式(适合印刷和论文)
  13. plt.savefig('plot.pdf', bbox_inches='tight', format='pdf')
  14. # 导出为SVG格式(矢量图,可无限缩放)
  15. plt.savefig('plot.svg', bbox_inches='tight', format='svg')
  16. # 导出为JPG格式(有损压缩,适合照片)
  17. plt.savefig('plot.jpg', dpi=300, bbox_inches='tight', quality=95)
  18. # 显示图形
  19. plt.show()
复制代码

总结与展望

Matplotlib作为Python数据可视化的核心库,提供了从基础到高级的全面绘图功能。通过本指南,我们学习了:

1. Matplotlib的基本概念和安装方法
2. 各种基本图表的绘制方法,包括线图、散点图、柱状图和饼图
3. 图表定制技巧,包括标题、标签、颜色和线型等
4. 多子图绘制方法,包括规则和不规则布局
5. 高级可视化技术,如3D图、等高线图、热图和极坐标图
6. 统计图表的绘制,包括直方图、箱线图、误差棒图和面积图
7. 动画和交互式图表的创建
8. 数据分析和科研中的实际应用案例
9. 提高绘图效率和美化图表的最佳实践

随着数据科学和可视化技术的不断发展,Matplotlib也在持续更新和改进。未来,我们可以期待更多高级功能和更便捷的API。同时,Matplotlib与其他Python库(如Pandas、Seaborn、Plotly等)的结合使用,将进一步扩展Python数据可视化的能力和应用范围。

掌握Matplotlib不仅能够满足日常数据可视化的需求,还能为深入学习其他可视化工具打下坚实基础。希望本指南能够帮助您在数据分析和科研工作中更好地利用Matplotlib进行数据可视化,从而更有效地展示和传达数据中的信息。
回复

使用道具 举报

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

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.