简体中文 繁體中文 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-8-24 18:40:01 | 显示全部楼层 |阅读模式

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

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

x
1. 引言

Matplotlib是Python中最流行的数据可视化库之一,它为Python提供了强大的绘图功能,能够生成各种静态、动态和交互式的图表。作为Python数据科学生态系统的核心组件,Matplotlib与NumPy、Pandas等库紧密集成,成为数据分析师和科学家不可或缺的工具。

本教程将带您从Matplotlib的基础知识开始,逐步深入到高级数据可视化技术,帮助您掌握使用Matplotlib进行数据分析可视化的全面技能。

2. Matplotlib基础

2.1 安装和导入

在开始使用Matplotlib之前,首先需要安装该库。可以使用pip进行安装:
  1. pip install matplotlib
复制代码

安装完成后,在Python脚本或Jupyter Notebook中导入Matplotlib:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
复制代码

通常,我们也会导入NumPy,因为它提供了强大的数组操作功能,与Matplotlib配合使用非常方便。

2.2 Matplotlib的基本概念

Matplotlib的核心概念是Figure(图形)和Axes(坐标系)。

• Figure:整个图形窗口,可以包含一个或多个Axes。
• Axes:实际的绘图区域,包含坐标轴、标题、标签等。

创建一个简单的Figure和Axes:
  1. # 创建一个Figure和一个Axes
  2. fig, ax = plt.subplots()
  3. # 显示图形
  4. plt.show()
复制代码

2.3 第一个简单图表

让我们创建一个简单的线图:
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y = np.sin(x)
  4. # 创建Figure和Axes
  5. fig, ax = plt.subplots()
  6. # 绘制线图
  7. ax.plot(x, y)
  8. # 显示图形
  9. plt.show()
复制代码

这段代码将生成一个简单的正弦波图表。

3. 基础绘图

3.1 线图

线图是最基本的图表类型,适合展示数据随时间或连续变量的变化趋势。
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots()
  7. # 绘制两条线
  8. ax.plot(x, y1, label='sin(x)')
  9. ax.plot(x, y2, label='cos(x)')
  10. # 添加图例
  11. ax.legend()
  12. # 添加标题和标签
  13. ax.set_title('三角函数')
  14. ax.set_xlabel('x')
  15. ax.set_ylabel('y')
  16. # 显示图形
  17. plt.show()
复制代码

3.2 散点图

散点图适合展示两个变量之间的关系。
  1. # 生成随机数据
  2. np.random.seed(42)
  3. x = np.random.randn(100)
  4. y = x + np.random.randn(100) * 0.5
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots()
  7. # 绘制散点图
  8. ax.scatter(x, y, alpha=0.6)
  9. # 添加标题和标签
  10. ax.set_title('散点图示例')
  11. ax.set_xlabel('x')
  12. ax.set_ylabel('y')
  13. # 显示图形
  14. plt.show()
复制代码

3.3 柱状图

柱状图适合比较不同类别的数据。
  1. # 准备数据
  2. categories = ['A', 'B', 'C', 'D', 'E']
  3. values = [7, 12, 4, 8, 15]
  4. # 创建Figure和Axes
  5. fig, ax = plt.subplots()
  6. # 绘制柱状图
  7. ax.bar(categories, values)
  8. # 添加标题和标签
  9. ax.set_title('柱状图示例')
  10. ax.set_xlabel('类别')
  11. ax.set_ylabel('值')
  12. # 显示图形
  13. plt.show()
复制代码

3.4 饼图

饼图适合展示各部分占整体的比例。
  1. # 准备数据
  2. sizes = [15, 30, 45, 10]
  3. labels = ['A', 'B', 'C', 'D']
  4. explode = (0, 0.1, 0, 0)  # 突出第二块
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots()
  7. # 绘制饼图
  8. ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
  9.        shadow=True, startangle=90)
  10. # 确保饼图是圆形的
  11. ax.axis('equal')
  12. # 添加标题
  13. ax.set_title('饼图示例')
  14. # 显示图形
  15. plt.show()
复制代码

4. 图表定制

4.1 颜色、线型和标记

Matplotlib提供了丰富的选项来自定义图表的外观。
  1. # 准备数据
  2. x = np.linspace(0, 10, 20)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots()
  7. # 绘制不同样式的线
  8. ax.plot(x, y1, 'r--', label='sin(x)')  # 红色虚线
  9. ax.plot(x, y2, 'b-o', label='cos(x)')  # 蓝色实线带圆点标记
  10. # 添加图例
  11. ax.legend()
  12. # 添加标题和标签
  13. ax.set_title('自定义线型和标记')
  14. ax.set_xlabel('x')
  15. ax.set_ylabel('y')
  16. # 显示图形
  17. plt.show()
复制代码

4.2 文本和注释

可以在图表中添加文本和注释来强调重要信息。
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y = np.sin(x)
  4. # 创建Figure和Axes
  5. fig, ax = plt.subplots()
  6. # 绘制线图
  7. ax.plot(x, y)
  8. # 添加标题和标签
  9. ax.set_title('正弦波')
  10. ax.set_xlabel('x')
  11. ax.set_ylabel('y')
  12. # 添加文本
  13. ax.text(5, 0.5, '正弦波', fontsize=12)
  14. # 添加注释
  15. ax.annotate('最大值', xy=(np.pi/2, 1), xytext=(3, 0.5),
  16.             arrowprops=dict(facecolor='black', shrink=0.05))
  17. # 显示图形
  18. plt.show()
复制代码

4.3 坐标轴设置

可以自定义坐标轴的范围、刻度和标签。
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y = np.sin(x)
  4. # 创建Figure和Axes
  5. fig, ax = plt.subplots()
  6. # 绘制线图
  7. ax.plot(x, y)
  8. # 设置坐标轴范围
  9. ax.set_xlim(0, 10)
  10. ax.set_ylim(-1.5, 1.5)
  11. # 设置坐标轴刻度
  12. ax.set_xticks(np.arange(0, 11, 2))
  13. ax.set_yticks(np.arange(-1.5, 2, 0.5))
  14. # 设置坐标轴标签
  15. ax.set_xticklabels(['0', '2π', '4π', '6π', '8π', '10π'])
  16. ax.set_yticklabels(['-1.5', '-1.0', '-0.5', '0.0', '0.5', '1.0', '1.5'])
  17. # 添加标题和标签
  18. ax.set_title('自定义坐标轴')
  19. ax.set_xlabel('x')
  20. ax.set_ylabel('y')
  21. # 显示图形
  22. plt.show()
复制代码

5. 多子图绘制

5.1 使用subplots创建多个子图
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. y3 = np.tan(x)
  6. y4 = np.exp(x/10)
  7. # 创建2x2的子图网格
  8. fig, axs = plt.subplots(2, 2, figsize=(12, 10))
  9. # 在第一个子图中绘制正弦波
  10. axs[0, 0].plot(x, y1)
  11. axs[0, 0].set_title('sin(x)')
  12. # 在第二个子图中绘制余弦波
  13. axs[0, 1].plot(x, y2)
  14. axs[0, 1].set_title('cos(x)')
  15. # 在第三个子图中绘制正切波
  16. axs[1, 0].plot(x, y3)
  17. axs[1, 0].set_title('tan(x)')
  18. axs[1, 0].set_ylim(-5, 5)  # 限制y轴范围,因为tan(x)在某些点趋向无穷大
  19. # 在第四个子图中绘制指数函数
  20. axs[1, 1].plot(x, y4)
  21. axs[1, 1].set_title('exp(x/10)')
  22. # 调整子图间距
  23. plt.tight_layout()
  24. # 显示图形
  25. plt.show()
复制代码

5.2 使用GridSpec创建复杂的子图布局
  1. # 导入GridSpec
  2. from matplotlib.gridspec import GridSpec
  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. # 创建Figure和GridSpec
  9. fig = plt.figure(figsize=(12, 8))
  10. gs = GridSpec(3, 2, figure=fig)
  11. # 创建不同大小的子图
  12. ax1 = fig.add_subplot(gs[0, 0])  # 第一行第一列
  13. ax2 = fig.add_subplot(gs[0, 1])  # 第一行第二列
  14. ax3 = fig.add_subplot(gs[1:, :])  # 占据剩余所有行和所有列
  15. # 在子图中绘制数据
  16. ax1.plot(x, y1)
  17. ax1.set_title('sin(x)')
  18. ax2.plot(x, y2)
  19. ax2.set_title('cos(x)')
  20. ax3.plot(x, y3)
  21. ax3.set_title('sin(x) * cos(x)')
  22. # 调整子图间距
  23. plt.tight_layout()
  24. # 显示图形
  25. plt.show()
复制代码

5.3 共享坐标轴
  1. # 准备数据
  2. x = np.linspace(0, 10, 100)
  3. y1 = np.sin(x)
  4. y2 = np.cos(x)
  5. # 创建共享x轴的子图
  6. fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 8))
  7. # 在第一个子图中绘制正弦波
  8. ax1.plot(x, y1)
  9. ax1.set_title('sin(x)')
  10. # 在第二个子图中绘制余弦波
  11. ax2.plot(x, y2)
  12. ax2.set_title('cos(x)')
  13. # 设置x轴标签
  14. ax2.set_xlabel('x')
  15. # 调整子图间距
  16. plt.tight_layout()
  17. # 显示图形
  18. plt.show()
复制代码

6. 高级图表类型

6.1 热图

热图适合展示矩阵数据或二维分布。
  1. # 生成随机数据
  2. data = np.random.randn(10, 10)
  3. # 创建Figure和Axes
  4. fig, ax = plt.subplots(figsize=(8, 6))
  5. # 绘制热图
  6. im = ax.imshow(data, cmap='coolwarm')
  7. # 添加颜色条
  8. cbar = fig.colorbar(im, ax=ax)
  9. # 设置标题
  10. ax.set_title('热图示例')
  11. # 显示图形
  12. plt.show()
复制代码

6.2 等高线图

等高线图适合展示三维数据的二维投影。
  1. # 创建网格数据
  2. x = np.linspace(-3.0, 3.0, 100)
  3. y = np.linspace(-3.0, 3.0, 100)
  4. X, Y = np.meshgrid(x, y)
  5. # 计算Z值
  6. Z = np.exp(-(X**2 + Y**2))
  7. # 创建Figure和Axes
  8. fig, ax = plt.subplots(figsize=(8, 6))
  9. # 绘制等高线图
  10. contour = ax.contour(X, Y, Z, cmap='viridis')
  11. # 添加等高线标签
  12. ax.clabel(contour, inline=True, fontsize=8)
  13. # 设置标题
  14. ax.set_title('等高线图示例')
  15. # 显示图形
  16. plt.show()
复制代码

6.3 3D图

Matplotlib也支持创建3D图表。
  1. # 导入3D绘图工具
  2. from mpl_toolkits.mplot3d import Axes3D
  3. # 创建网格数据
  4. x = np.linspace(-5, 5, 50)
  5. y = np.linspace(-5, 5, 50)
  6. X, Y = np.meshgrid(x, y)
  7. # 计算Z值
  8. Z = np.sin(np.sqrt(X**2 + Y**2))
  9. # 创建Figure和3D Axes
  10. fig = plt.figure(figsize=(10, 8))
  11. ax = fig.add_subplot(111, projection='3d')
  12. # 绘制3D表面图
  13. surf = ax.plot_surface(X, Y, Z, cmap='viridis')
  14. # 添加颜色条
  15. fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
  16. # 设置标题和标签
  17. ax.set_title('3D表面图示例')
  18. ax.set_xlabel('X')
  19. ax.set_ylabel('Y')
  20. ax.set_zlabel('Z')
  21. # 显示图形
  22. plt.show()
复制代码

7. 统计图表

7.1 直方图

直方图适合展示数据的分布情况。
  1. # 生成随机数据
  2. np.random.seed(42)
  3. data = np.random.normal(0, 1, 1000)
  4. # 创建Figure和Axes
  5. fig, ax = plt.subplots(figsize=(10, 6))
  6. # 绘制直方图
  7. ax.hist(data, bins=30, density=True, alpha=0.7, color='blue')
  8. # 添加核密度估计曲线
  9. from scipy.stats import gaussian_kde
  10. kde = gaussian_kde(data)
  11. x_range = np.linspace(min(data), max(data), 100)
  12. ax.plot(x_range, kde(x_range), 'r-', linewidth=2)
  13. # 添加标题和标签
  14. ax.set_title('直方图与核密度估计')
  15. ax.set_xlabel('值')
  16. ax.set_ylabel('密度')
  17. # 显示图形
  18. plt.show()
复制代码

7.2 箱线图

箱线图适合展示数据的分布和异常值。
  1. # 生成随机数据
  2. np.random.seed(42)
  3. data1 = np.random.normal(0, 1, 100)
  4. data2 = np.random.normal(1, 1.5, 100)
  5. data3 = np.random.normal(-1, 0.5, 100)
  6. # 创建Figure和Axes
  7. fig, ax = plt.subplots(figsize=(10, 6))
  8. # 绘制箱线图
  9. ax.boxplot([data1, data2, data3], labels=['组1', '组2', '组3'])
  10. # 添加标题
  11. ax.set_title('箱线图示例')
  12. # 显示图形
  13. plt.show()
复制代码

7.3 小提琴图

小提琴图结合了箱线图和核密度估计的优点。
  1. # 生成随机数据
  2. np.random.seed(42)
  3. data1 = np.random.normal(0, 1, 100)
  4. data2 = np.random.normal(1, 1.5, 100)
  5. data3 = np.random.normal(-1, 0.5, 100)
  6. # 创建Figure和Axes
  7. fig, ax = plt.subplots(figsize=(10, 6))
  8. # 绘制小提琴图
  9. ax.violinplot([data1, data2, data3], showmeans=True, showmedians=True)
  10. # 设置x轴标签
  11. ax.set_xticks([1, 2, 3])
  12. ax.set_xticklabels(['组1', '组2', '组3'])
  13. # 添加标题
  14. ax.set_title('小提琴图示例')
  15. # 显示图形
  16. plt.show()
复制代码

8. 交互式图表

8.1 使用matplotlib.widgets创建交互式控件
  1. # 导入必要的模块
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. from matplotlib.widgets import Slider, Button
  5. # 创建初始数据
  6. x = np.linspace(0, 10, 1000)
  7. y = np.sin(x)
  8. # 创建Figure和Axes
  9. fig, ax = plt.subplots(figsize=(10, 6))
  10. plt.subplots_adjust(bottom=0.25)  # 为滑块留出空间
  11. # 绘制初始线图
  12. line, = ax.plot(x, y, lw=2)
  13. # 设置坐标轴范围
  14. ax.set_xlim(0, 10)
  15. ax.set_ylim(-1.5, 1.5)
  16. # 添加标题和标签
  17. ax.set_title('交互式正弦波')
  18. ax.set_xlabel('x')
  19. ax.set_ylabel('y')
  20. # 创建滑块轴
  21. ax_freq = plt.axes([0.25, 0.1, 0.65, 0.03])
  22. ax_amp = plt.axes([0.25, 0.15, 0.65, 0.03])
  23. # 创建滑块
  24. freq_slider = Slider(ax_freq, '频率', 0.1, 5.0, valinit=1.0)
  25. amp_slider = Slider(ax_amp, '振幅', 0.1, 2.0, valinit=1.0)
  26. # 定义更新函数
  27. def update(val):
  28.     freq = freq_slider.val
  29.     amp = amp_slider.val
  30.     line.set_ydata(amp * np.sin(freq * x))
  31.     fig.canvas.draw_idle()
  32. # 注册更新函数
  33. freq_slider.on_changed(update)
  34. amp_slider.on_changed(update)
  35. # 创建重置按钮
  36. resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
  37. button = Button(resetax, '重置')
  38. # 定义重置函数
  39. def reset(event):
  40.     freq_slider.reset()
  41.     amp_slider.reset()
  42. # 注册重置函数
  43. button.on_clicked(reset)
  44. # 显示图形
  45. plt.show()
复制代码

8.2 使用mplcursors创建交互式数据提示
  1. # 安装mplcursors(如果尚未安装)
  2. # pip install mplcursors
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import mplcursors
  6. # 生成随机数据
  7. np.random.seed(42)
  8. x = np.arange(10)
  9. y = np.random.rand(10)
  10. # 创建Figure和Axes
  11. fig, ax = plt.subplots(figsize=(10, 6))
  12. # 绘制散点图
  13. scatter = ax.scatter(x, y)
  14. # 添加标题和标签
  15. ax.set_title('交互式散点图')
  16. ax.set_xlabel('x')
  17. ax.set_ylabel('y')
  18. # 添加光标交互
  19. cursor = mplcursors.cursor(scatter, hover=True)
  20. # 显示图形
  21. plt.show()
复制代码

9. 动画

9.1 使用FuncAnimation创建简单动画
  1. # 导入必要的模块
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. from matplotlib.animation import FuncAnimation
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots(figsize=(10, 6))
  7. # 设置坐标轴范围
  8. ax.set_xlim(0, 10)
  9. ax.set_ylim(-1.5, 1.5)
  10. # 添加标题和标签
  11. ax.set_title('正弦波动画')
  12. ax.set_xlabel('x')
  13. ax.set_ylabel('y')
  14. # 创建线对象
  15. line, = ax.plot([], [], lw=2)
  16. # 初始化函数
  17. def init():
  18.     line.set_data([], [])
  19.     return line,
  20. # 更新函数
  21. def update(frame):
  22.     x = np.linspace(0, 10, 1000)
  23.     y = np.sin(2 * np.pi * (x - 0.1 * frame))
  24.     line.set_data(x, y)
  25.     return line,
  26. # 创建动画
  27. ani = FuncAnimation(fig, update, frames=100, init_func=init,
  28.                     blit=True, interval=50)
  29. # 显示动画
  30. plt.show()
复制代码

9.2 保存动画
  1. # 导入必要的模块
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. from matplotlib.animation import FuncAnimation, PillowWriter
  5. # 创建Figure和Axes
  6. fig, ax = plt.subplots(figsize=(10, 6))
  7. # 设置坐标轴范围
  8. ax.set_xlim(0, 10)
  9. ax.set_ylim(-1.5, 1.5)
  10. # 添加标题和标签
  11. ax.set_title('正弦波动画')
  12. ax.set_xlabel('x')
  13. ax.set_ylabel('y')
  14. # 创建线对象
  15. line, = ax.plot([], [], lw=2)
  16. # 初始化函数
  17. def init():
  18.     line.set_data([], [])
  19.     return line,
  20. # 更新函数
  21. def update(frame):
  22.     x = np.linspace(0, 10, 1000)
  23.     y = np.sin(2 * np.pi * (x - 0.1 * frame))
  24.     line.set_data(x, y)
  25.     return line,
  26. # 创建动画
  27. ani = FuncAnimation(fig, update, frames=100, init_func=init,
  28.                     blit=True, interval=50)
  29. # 保存动画为GIF
  30. writer = PillowWriter(fps=20)
  31. ani.save('sine_wave.gif', writer=writer)
  32. # 显示动画
  33. plt.show()
复制代码

10. 与其他库的集成

10.1 与Pandas集成

Matplotlib与Pandas数据框无缝集成,可以直接使用Pandas数据框进行绘图。
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. # 创建Pandas数据框
  5. np.random.seed(42)
  6. dates = pd.date_range('20230101', periods=100)
  7. data = pd.DataFrame({
  8.     'A': np.random.randn(100).cumsum(),
  9.     'B': np.random.randn(100).cumsum(),
  10.     'C': np.random.randn(100).cumsum()
  11. }, index=dates)
  12. # 创建Figure和Axes
  13. fig, ax = plt.subplots(figsize=(12, 6))
  14. # 使用Pandas的plot方法
  15. data.plot(ax=ax)
  16. # 添加标题和标签
  17. ax.set_title('Pandas数据框绘图')
  18. ax.set_xlabel('日期')
  19. ax.set_ylabel('值')
  20. # 显示图形
  21. plt.show()
复制代码

10.2 与Seaborn集成

Seaborn是基于Matplotlib的高级可视化库,可以与Matplotlib结合使用。
  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import pandas as pd
  5. # 创建示例数据
  6. np.random.seed(42)
  7. data = pd.DataFrame({
  8.     'x': np.random.randn(100),
  9.     'y': np.random.randn(100),
  10.     'category': np.random.choice(['A', 'B', 'C'], 100)
  11. })
  12. # 创建Figure和Axes
  13. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
  14. # 使用Seaborn绘制散点图
  15. sns.scatterplot(x='x', y='y', hue='category', data=data, ax=ax1)
  16. ax1.set_title('Seaborn散点图')
  17. # 使用Seaborn绘制箱线图
  18. sns.boxplot(x='category', y='y', data=data, ax=ax2)
  19. ax2.set_title('Seaborn箱线图')
  20. # 调整子图间距
  21. plt.tight_layout()
  22. # 显示图形
  23. plt.show()
复制代码

11. 最佳实践和技巧

11.1 选择合适的图表类型

不同的数据类型和分析目标需要不同的图表类型:

• 时间序列数据:线图
• 比较类别:柱状图、饼图
• 显示分布:直方图、箱线图、小提琴图
• 显示关系:散点图、热图
• 显示组成:堆叠柱状图、饼图

11.2 颜色选择

选择合适的颜色方案可以提高图表的可读性和美观度:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import matplotlib.colors as mcolors
  4. # 创建示例数据
  5. x = np.linspace(0, 10, 100)
  6. y1 = np.sin(x)
  7. y2 = np.cos(x)
  8. y3 = np.sin(x) * np.cos(x)
  9. # 创建Figure和Axes
  10. fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
  11. # 使用默认颜色
  12. ax1.plot(x, y1, label='sin(x)')
  13. ax1.plot(x, y2, label='cos(x)')
  14. ax1.plot(x, y3, label='sin(x)*cos(x)')
  15. ax1.set_title('默认颜色')
  16. ax1.legend()
  17. # 使用自定义颜色
  18. colors = ['#1f77b4', '#ff7f0e', '#2ca02c']  # 使用十六进制颜色代码
  19. ax2.plot(x, y1, color=colors[0], label='sin(x)')
  20. ax2.plot(x, y2, color=colors[1], label='cos(x)')
  21. ax2.plot(x, y3, color=colors[2], label='sin(x)*cos(x)')
  22. ax2.set_title('自定义颜色')
  23. ax2.legend()
  24. # 显示图形
  25. plt.show()
复制代码

11.3 图表布局和排版

良好的布局和排版可以使图表更加清晰和专业:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from matplotlib.gridspec import GridSpec
  4. # 创建示例数据
  5. x = np.linspace(0, 10, 100)
  6. y1 = np.sin(x)
  7. y2 = np.cos(x)
  8. categories = ['A', 'B', 'C', 'D']
  9. values = [7, 12, 4, 8]
  10. # 创建Figure和GridSpec
  11. fig = plt.figure(figsize=(15, 10))
  12. gs = GridSpec(2, 2, figure=fig, width_ratios=[2, 1], height_ratios=[2, 1])
  13. # 创建子图
  14. ax1 = fig.add_subplot(gs[0, 0])  # 大图
  15. ax2 = fig.add_subplot(gs[0, 1])  # 小图
  16. ax3 = fig.add_subplot(gs[1, :])  # 底部宽图
  17. # 在第一个子图中绘制正弦波和余弦波
  18. ax1.plot(x, y1, label='sin(x)')
  19. ax1.plot(x, y2, label='cos(x)')
  20. ax1.set_title('三角函数')
  21. ax1.legend()
  22. # 在第二个子图中绘制柱状图
  23. ax2.bar(categories, values)
  24. ax2.set_title('柱状图')
  25. # 在第三个子图中绘制正弦波和余弦波的乘积
  26. ax3.plot(x, y1 * y2, label='sin(x)*cos(x)')
  27. ax3.set_title('乘积函数')
  28. ax3.legend()
  29. # 添加总标题
  30. fig.suptitle('多子图布局示例', fontsize=16)
  31. # 调整子图间距
  32. plt.tight_layout(rect=[0, 0, 1, 0.96])  # 为总标题留出空间
  33. # 显示图形
  34. plt.show()
复制代码

11.4 导出高质量图像

Matplotlib支持多种图像格式,可以根据需要选择合适的格式和分辨率:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建示例数据
  4. x = np.linspace(0, 10, 100)
  5. y = np.sin(x)
  6. # 创建Figure和Axes
  7. fig, ax = plt.subplots(figsize=(10, 6))
  8. # 绘制线图
  9. ax.plot(x, y)
  10. # 添加标题和标签
  11. ax.set_title('正弦波')
  12. ax.set_xlabel('x')
  13. ax.set_ylabel('y')
  14. # 保存为PNG格式(高分辨率)
  15. plt.savefig('sine_wave.png', dpi=300, bbox_inches='tight')
  16. # 保存为PDF格式(矢量图,适合出版)
  17. plt.savefig('sine_wave.pdf', bbox_inches='tight')
  18. # 保存为SVG格式(矢量图,适合网页)
  19. plt.savefig('sine_wave.svg', bbox_inches='tight')
  20. # 显示图形
  21. plt.show()
复制代码

12. 实际案例

12.1 分析销售数据
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import seaborn as sns
  5. # 创建示例销售数据
  6. np.random.seed(42)
  7. dates = pd.date_range('20220101', periods=365)
  8. products = ['A', 'B', 'C', 'D']
  9. regions = ['North', 'South', 'East', 'West']
  10. # 生成随机销售数据
  11. data = []
  12. for date in dates:
  13.     for product in products:
  14.         for region in regions:
  15.             base_sales = np.random.randint(100, 500)
  16.             seasonal_factor = 1 + 0.2 * np.sin(2 * np.pi * (date.dayofyear / 365))
  17.             sales = int(base_sales * seasonal_factor)
  18.             data.append([date, product, region, sales])
  19. # 创建数据框
  20. df = pd.DataFrame(data, columns=['Date', 'Product', 'Region', 'Sales'])
  21. # 按日期汇总销售数据
  22. daily_sales = df.groupby('Date')['Sales'].sum().reset_index()
  23. # 创建Figure和Axes
  24. fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 12))
  25. # 绘制销售趋势图
  26. ax1.plot(daily_sales['Date'], daily_sales['Sales'])
  27. ax1.set_title('每日销售趋势')
  28. ax1.set_xlabel('日期')
  29. ax1.set_ylabel('销售额')
  30. ax1.grid(True)
  31. # 按产品和地区汇总销售数据
  32. product_sales = df.groupby('Product')['Sales'].sum()
  33. region_sales = df.groupby('Region')['Sales'].sum()
  34. # 绘制产品销售饼图
  35. ax2.pie(product_sales, labels=product_sales.index, autopct='%1.1f%%')
  36. ax2.set_title('产品销售占比')
  37. # 调整子图间距
  38. plt.tight_layout()
  39. # 显示图形
  40. plt.show()
  41. # 创建另一个图来比较不同地区的销售情况
  42. fig, ax = plt.subplots(figsize=(12, 6))
  43. # 创建透视表
  44. pivot_df = df.pivot_table(index='Date', columns='Region', values='Sales', aggfunc='sum')
  45. # 绘制各地区销售趋势
  46. for region in regions:
  47.     ax.plot(pivot_df.index, pivot_df[region], label=region)
  48. # 添加标题和标签
  49. ax.set_title('各地区销售趋势比较')
  50. ax.set_xlabel('日期')
  51. ax.set_ylabel('销售额')
  52. ax.legend()
  53. # 显示图形
  54. plt.show()
复制代码

12.2 分析金融数据
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import yfinance as yf  # 需要安装:pip install yfinance
  5. # 下载股票数据
  6. tickers = ['AAPL', 'MSFT', 'GOOG', 'AMZN']
  7. start_date = '2020-01-01'
  8. end_date = '2023-01-01'
  9. data = yf.download(tickers, start=start_date, end=end_date)['Adj Close']
  10. # 计算日收益率
  11. returns = data.pct_change().dropna()
  12. # 创建Figure和Axes
  13. fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 12))
  14. # 绘制股票价格走势
  15. for ticker in tickers:
  16.     ax1.plot(data.index, data[ticker], label=ticker)
  17. # 添加标题和标签
  18. ax1.set_title('股票价格走势')
  19. ax1.set_xlabel('日期')
  20. ax1.set_ylabel('价格')
  21. ax1.legend()
  22. ax1.grid(True)
  23. # 绘制收益率分布
  24. for ticker in tickers:
  25.     ax2.hist(returns[ticker], bins=50, alpha=0.5, label=ticker)
  26. # 添加标题和标签
  27. ax2.set_title('收益率分布')
  28. ax2.set_xlabel('日收益率')
  29. ax2.set_ylabel('频数')
  30. ax2.legend()
  31. # 调整子图间距
  32. plt.tight_layout()
  33. # 显示图形
  34. plt.show()
  35. # 创建另一个图来显示相关性热图
  36. fig, ax = plt.subplots(figsize=(10, 8))
  37. # 计算相关系数矩阵
  38. corr_matrix = returns.corr()
  39. # 绘制热图
  40. im = ax.imshow(corr_matrix, cmap='coolwarm')
  41. # 设置刻度标签
  42. ax.set_xticks(np.arange(len(tickers)))
  43. ax.set_yticks(np.arange(len(tickers)))
  44. ax.set_xticklabels(tickers)
  45. ax.set_yticklabels(tickers)
  46. # 在热图上显示相关系数
  47. for i in range(len(tickers)):
  48.     for j in range(len(tickers)):
  49.         text = ax.text(j, i, f'{corr_matrix.iloc[i, j]:.2f}',
  50.                       ha="center", va="center", color="black")
  51. # 添加标题
  52. ax.set_title('股票收益率相关性热图')
  53. # 添加颜色条
  54. cbar = fig.colorbar(im, ax=ax)
  55. # 显示图形
  56. plt.show()
复制代码

13. 总结

Matplotlib是Python数据科学生态系统中不可或缺的可视化工具,它提供了从基础绘图到高级数据可视化的全面功能。通过本教程,我们学习了:

1. Matplotlib的基础概念和使用方法
2. 各种基础图表类型的创建和定制
3. 多子图的创建和布局
4. 高级图表类型,如热图、等高线图和3D图
5. 统计图表,如直方图、箱线图和小提琴图
6. 交互式图表的创建
7. 动画的制作和保存
8. 与Pandas和Seaborn等其他库的集成
9. 数据可视化的最佳实践和技巧
10. 实际案例分析

要进一步掌握Matplotlib,建议:

1. 多练习不同类型的图表创建
2. 阅读Matplotlib官方文档和示例
3. 尝试解决真实的数据分析问题
4. 学习更高级的可视化技术,如地理空间可视化
5. 探索Matplotlib的扩展库,如mpld3(交互式3D图表)

随着数据科学和人工智能的发展,数据可视化变得越来越重要。掌握Matplotlib将帮助您更好地理解和传达数据中的洞察,为您的数据分析工作增添强大的视觉表达能力。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则

关闭

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

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

Powered by Pixtech

© 2025-2026 Pixtech Team.

>