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

站内搜索

搜索

活动公告

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

精通Matplotlib网格化图表布局技巧轻松创建专业数据可视化作品大幅提升分析效率和展示效果

SunJu_FaceMall

3万

主题

1174

科技点

3万

积分

白金月票

碾压王

积分
32796

立华奏

发表于 2025-8-24 15:00:00 | 显示全部楼层 |阅读模式

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

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

x
引言

Matplotlib是Python中最流行的数据可视化库之一,它提供了丰富的功能来创建各种类型的图表。在数据分析、科学研究和商业报告中,我们经常需要在一个图形中展示多个图表,以便进行对比分析或全面展示数据的不同方面。网格化图表布局是实现这一目标的关键技术,它允许我们在一个画布上创建多个子图,并灵活控制它们的位置、大小和间距。

掌握Matplotlib的网格化布局技巧,不仅能大幅提升数据分析效率,还能让我们的可视化作品更加专业、美观,从而更有效地传达信息。本文将详细介绍Matplotlib中各种网格化布局的方法和技巧,从基础的subplot到高级的GridSpec,帮助读者轻松创建专业的数据可视化作品。

Matplotlib基础回顾

在深入了解网格化布局之前,让我们先回顾一些Matplotlib的基础概念。Matplotlib中的图形由几个关键组件组成:

• Figure:整个图形窗口或画布,可以包含一个或多个子图。
• Axes:子图,是实际绘制数据的区域,包括坐标轴、标题、标签等。
• Axis:坐标轴,包括x轴、y轴以及它们的刻度和标签。
• Artist:图形中的所有可见元素,包括文本、线条、图例等。

在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. # 创建图形和子图
  7. fig, ax = plt.subplots()
  8. # 绘制数据
  9. ax.plot(x, y)
  10. # 添加标题和标签
  11. ax.set_title('正弦函数')
  12. ax.set_xlabel('x')
  13. ax.set_ylabel('sin(x)')
  14. # 显示图形
  15. plt.show()
复制代码

现在,让我们开始探索如何在一个图形中创建多个子图。

使用plt.subplot()创建简单网格

plt.subplot()是Matplotlib中最基本的创建网格布局的方法。它允许我们将图形分割成规则的网格,并在指定的位置创建子图。

基本用法

plt.subplot(nrows, ncols, index)创建一个具有nrows行和ncols列的网格,并在index指定的位置创建子图。索引从1开始,从左到右、从上到下递增。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建2x2的网格
  10. plt.figure(figsize=(10, 8))
  11. # 第一个子图(左上)
  12. plt.subplot(2, 2, 1)
  13. plt.plot(x, y1)
  14. plt.title('正弦函数')
  15. # 第二个子图(右上)
  16. plt.subplot(2, 2, 2)
  17. plt.plot(x, y2)
  18. plt.title('余弦函数')
  19. # 第三个子图(左下)
  20. plt.subplot(2, 2, 3)
  21. plt.plot(x, y3)
  22. plt.title('正切函数')
  23. plt.ylim(-5, 5)  # 限制y轴范围,因为正切函数在某些点趋向于无穷大
  24. # 第四个子图(右下)
  25. plt.subplot(2, 2, 4)
  26. plt.plot(x, y4)
  27. plt.title('指数函数')
  28. # 调整子图间距
  29. plt.tight_layout()
  30. # 显示图形
  31. plt.show()
复制代码

使用逗号分隔的简写形式

plt.subplot()也接受一个三位数的整数作为参数,其中百位数表示行数,十位数表示列数,个位数表示索引。例如,plt.subplot(221)等同于plt.subplot(2, 2, 1)。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. # 创建2x1的网格
  8. plt.figure(figsize=(10, 6))
  9. # 第一个子图(上)
  10. plt.subplot(211)
  11. plt.plot(x, y1)
  12. plt.title('正弦函数')
  13. # 第二个子图(下)
  14. plt.subplot(212)
  15. plt.plot(x, y2)
  16. plt.title('余弦函数')
  17. # 调整子图间距
  18. plt.tight_layout()
  19. # 显示图形
  20. plt.show()
复制代码

创建不规则网格

plt.subplot()还可以创建不规则的网格,通过指定rowspan和colspan参数,让一个子图跨越多个行或列。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. # 创建图形
  9. plt.figure(figsize=(10, 8))
  10. # 第一个子图,跨越第一行的两列
  11. plt.subplot(2, 2, (1, 2))
  12. plt.plot(x, y1)
  13. plt.title('正弦函数')
  14. # 第二个子图,位于第二行第一列
  15. plt.subplot(2, 2, 3)
  16. plt.plot(x, y2)
  17. plt.title('余弦函数')
  18. # 第三个子图,位于第二行第二列
  19. plt.subplot(2, 2, 4)
  20. plt.plot(x, y3)
  21. plt.title('正切函数')
  22. plt.ylim(-5, 5)
  23. # 调整子图间距
  24. plt.tight_layout()
  25. # 显示图形
  26. plt.show()
复制代码

使用plt.subplots()创建更复杂的网格

plt.subplots()是另一种创建网格布局的方法,与plt.subplot()不同,它一次性创建所有子图,并返回一个包含图形和子图数组的元组。这种方法更适合创建规则的网格,并且可以更方便地对子图进行操作。

基本用法
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建2x2的网格
  10. fig, axes = plt.subplots(2, 2, figsize=(10, 8))
  11. # 绘制第一个子图(左上)
  12. axes[0, 0].plot(x, y1)
  13. axes[0, 0].set_title('正弦函数')
  14. # 绘制第二个子图(右上)
  15. axes[0, 1].plot(x, y2)
  16. axes[0, 1].set_title('余弦函数')
  17. # 绘制第三个子图(左下)
  18. axes[1, 0].plot(x, y3)
  19. axes[1, 0].set_title('正切函数')
  20. axes[1, 0].set_ylim(-5, 5)
  21. # 绘制第四个子图(右下)
  22. axes[1, 1].plot(x, y4)
  23. axes[1, 1].set_title('指数函数')
  24. # 调整子图间距
  25. plt.tight_layout()
  26. # 显示图形
  27. plt.show()
复制代码

共享x轴和y轴

plt.subplots()的一个强大功能是可以让子图共享x轴或y轴,这在比较相似数据时非常有用。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.sin(x) + 0.5 * np.cos(x)
  8. y4 = np.cos(x) + 0.5 * np.sin(x)
  9. # 创建2x2的网格,共享x轴和y轴
  10. fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True, sharey=True)
  11. # 绘制子图
  12. axes[0, 0].plot(x, y1)
  13. axes[0, 0].set_title('正弦函数')
  14. axes[0, 1].plot(x, y2)
  15. axes[0, 1].set_title('余弦函数')
  16. axes[1, 0].plot(x, y3)
  17. axes[1, 0].set_title('sin(x) + 0.5*cos(x)')
  18. axes[1, 1].plot(x, y4)
  19. axes[1, 1].set_title('cos(x) + 0.5*sin(x)')
  20. # 设置x轴和y轴标签
  21. for ax in axes.flat:
  22.     ax.set_xlabel('x')
  23.     ax.set_ylabel('y')
  24. # 调整子图间距
  25. plt.tight_layout()
  26. # 显示图形
  27. plt.show()
复制代码

创建一维子图数组

如果只需要一行或一列子图,plt.subplots()会返回一个一维数组,这使得操作更加简单。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. # 创建1x3的网格
  9. fig, axes = plt.subplots(1, 3, figsize=(15, 5))
  10. # 绘制子图
  11. axes[0].plot(x, y1)
  12. axes[0].set_title('正弦函数')
  13. axes[1].plot(x, y2)
  14. axes[1].set_title('余弦函数')
  15. axes[2].plot(x, y3)
  16. axes[2].set_title('正切函数')
  17. axes[2].set_ylim(-5, 5)
  18. # 调整子图间距
  19. plt.tight_layout()
  20. # 显示图形
  21. plt.show()
复制代码

使用GridSpec进行高级布局控制

GridSpec是Matplotlib中最灵活的网格布局工具,它允许我们创建复杂的、不规则的网格布局,并精确控制每个子图的位置和大小。

基本用法
  1. import matplotlib.pyplot as plt
  2. import matplotlib.gridspec as gridspec
  3. import numpy as np
  4. # 创建数据
  5. x = np.linspace(0, 10, 100)
  6. y1 = np.sin(x)
  7. y2 = np.cos(x)
  8. y3 = np.tan(x)
  9. y4 = np.exp(x/10)
  10. # 创建图形
  11. fig = plt.figure(figsize=(10, 8))
  12. # 创建GridSpec
  13. gs = gridspec.GridSpec(3, 3)
  14. # 创建子图
  15. # 第一个子图,跨越第一行的三列
  16. ax1 = fig.add_subplot(gs[0, :])
  17. ax1.plot(x, y1)
  18. ax1.set_title('正弦函数')
  19. # 第二个子图,位于第二行第一列
  20. ax2 = fig.add_subplot(gs[1, 0])
  21. ax2.plot(x, y2)
  22. ax2.set_title('余弦函数')
  23. # 第三个子图,位于第二行第二列和第三列
  24. ax3 = fig.add_subplot(gs[1, 1:])
  25. ax3.plot(x, y3)
  26. ax3.set_title('正切函数')
  27. ax3.set_ylim(-5, 5)
  28. # 第四个子图,位于第三行的三列
  29. ax4 = fig.add_subplot(gs[2, :])
  30. ax4.plot(x, y4)
  31. ax4.set_title('指数函数')
  32. # 调整子图间距
  33. plt.tight_layout()
  34. # 显示图形
  35. plt.show()
复制代码

使用GridSpec调整子图大小比例

GridSpec允许我们通过width_ratios和height_ratios参数来调整子图的宽高比例。
  1. import matplotlib.pyplot as plt
  2. import matplotlib.gridspec as gridspec
  3. import numpy as np
  4. # 创建数据
  5. x = np.linspace(0, 10, 100)
  6. y1 = np.sin(x)
  7. y2 = np.cos(x)
  8. y3 = np.tan(x)
  9. # 创建图形
  10. fig = plt.figure(figsize=(10, 8))
  11. # 创建GridSpec,设置宽度比例和高度比例
  12. gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[2, 1])
  13. # 创建子图
  14. # 第一个子图,位于第一行第一列
  15. ax1 = fig.add_subplot(gs[0, 0])
  16. ax1.plot(x, y1)
  17. ax1.set_title('正弦函数')
  18. # 第二个子图,位于第一行第二列
  19. ax2 = fig.add_subplot(gs[0, 1])
  20. ax2.plot(x, y2)
  21. ax2.set_title('余弦函数')
  22. # 第三个子图,跨越第二行的两列
  23. ax3 = fig.add_subplot(gs[1, :])
  24. ax3.plot(x, y3)
  25. ax3.set_title('正切函数')
  26. ax3.set_ylim(-5, 5)
  27. # 调整子图间距
  28. plt.tight_layout()
  29. # 显示图形
  30. plt.show()
复制代码

使用GridSpec创建嵌套布局

GridSpec还可以创建嵌套布局,即在一个子图中再创建一个更小的网格。
  1. import matplotlib.pyplot as plt
  2. import matplotlib.gridspec as gridspec
  3. import numpy as np
  4. # 创建数据
  5. x = np.linspace(0, 10, 100)
  6. y1 = np.sin(x)
  7. y2 = np.cos(x)
  8. y3 = np.tan(x)
  9. y4 = np.exp(x/10)
  10. # 创建图形
  11. fig = plt.figure(figsize=(12, 10))
  12. # 创建主GridSpec
  13. gs = gridspec.GridSpec(3, 3)
  14. # 创建大子图,跨越前两行的两列
  15. ax_big = fig.add_subplot(gs[:2, :2])
  16. ax_big.plot(x, y1)
  17. ax_big.set_title('正弦函数(大图)')
  18. # 创建小GridSpec,位于第一行第三列
  19. gs_small = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs[0, 2])
  20. # 在小GridSpec中创建子图
  21. ax_small1 = fig.add_subplot(gs_small[0])
  22. ax_small1.plot(x, y2)
  23. ax_small1.set_title('余弦函数')
  24. ax_small2 = fig.add_subplot(gs_small[1])
  25. ax_small2.plot(x, y3)
  26. ax_small2.set_title('正切函数')
  27. ax_small2.set_ylim(-5, 5)
  28. # 创建另一个子图,位于第二行第三列
  29. ax3 = fig.add_subplot(gs[1, 2])
  30. ax3.plot(x, y4)
  31. ax3.set_title('指数函数')
  32. # 创建底部子图,跨越第三行的三列
  33. ax_bottom = fig.add_subplot(gs[2, :])
  34. ax_bottom.plot(x, y1 + y2)
  35. ax_bottom.set_title('正弦函数 + 余弦函数')
  36. # 调整子图间距
  37. plt.tight_layout()
  38. # 显示图形
  39. plt.show()
复制代码

使用subplot2grid进行灵活布局

subplot2grid是另一种创建不规则网格布局的方法,它比GridSpec更简单,但仍然提供了很大的灵活性。

基本用法

subplot2grid(shape, loc, rowspan=1, colspan=1)接受四个参数:

• shape:网格的形状,表示为(rows, cols)
• loc:子图的起始位置,表示为(row, col)
• rowspan:子图跨越的行数(默认为1)
• colspan:子图跨越的列数(默认为1)
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建图形
  10. fig = plt.figure(figsize=(10, 8))
  11. # 创建子图
  12. # 第一个子图,位于(0,0),跨越2行
  13. ax1 = plt.subplot2grid((3, 3), (0, 0), rowspan=2)
  14. ax1.plot(x, y1)
  15. ax1.set_title('正弦函数')
  16. # 第二个子图,位于(0,1),跨越1行2列
  17. ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
  18. ax2.plot(x, y2)
  19. ax2.set_title('余弦函数')
  20. # 第三个子图,位于(1,1)
  21. ax3 = plt.subplot2grid((3, 3), (1, 1))
  22. ax3.plot(x, y3)
  23. ax3.set_title('正切函数')
  24. ax3.set_ylim(-5, 5)
  25. # 第四个子图,位于(1,2)
  26. ax4 = plt.subplot2grid((3, 3), (1, 2))
  27. ax4.plot(x, y4)
  28. ax4.set_title('指数函数')
  29. # 第五个子图,位于(2,0),跨越1行3列
  30. ax5 = plt.subplot2grid((3, 3), (2, 0), colspan=3)
  31. ax5.plot(x, y1 + y2)
  32. ax5.set_title('正弦函数 + 余弦函数')
  33. # 调整子图间距
  34. plt.tight_layout()
  35. # 显示图形
  36. plt.show()
复制代码

创建复杂的仪表板布局

subplot2grid特别适合创建复杂的仪表板布局,让我们看一个更复杂的例子:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. np.random.seed(42)
  5. data = np.random.randn(100, 5)
  6. x = np.linspace(0, 10, 100)
  7. y1 = np.sin(x)
  8. y2 = np.cos(x)
  9. y3 = np.cumsum(np.random.randn(100))
  10. # 创建图形
  11. fig = plt.figure(figsize=(15, 10))
  12. # 创建标题
  13. fig.suptitle('数据分析仪表板', fontsize=16)
  14. # 创建主图表,位于(0,0),跨越2行2列
  15. ax_main = plt.subplot2grid((4, 4), (0, 0), colspan=2, rowspan=2)
  16. ax_main.plot(x, y1, label='正弦函数')
  17. ax_main.plot(x, y2, label='余弦函数')
  18. ax_main.set_title('主要趋势')
  19. ax_main.legend()
  20. # 创建柱状图,位于(0,2)
  21. ax_bar = plt.subplot2grid((4, 4), (0, 2))
  22. ax_bar.bar(range(5), np.mean(data, axis=0))
  23. ax_bar.set_title('平均值')
  24. # 创建饼图,位于(0,3)
  25. ax_pie = plt.subplot2grid((4, 4), (0, 3))
  26. ax_pie.pie(np.abs(np.mean(data, axis=0)), labels=['A', 'B', 'C', 'D', 'E'], autopct='%1.1f%%')
  27. ax_pie.set_title('比例分布')
  28. # 创建箱线图,位于(1,2)
  29. ax_box = plt.subplot2grid((4, 4), (1, 2))
  30. ax_box.boxplot(data)
  31. ax_box.set_title('数据分布')
  32. # 创建散点图,位于(1,3)
  33. ax_scatter = plt.subplot2grid((4, 4), (1, 3))
  34. ax_scatter.scatter(data[:, 0], data[:, 1])
  35. ax_scatter.set_title('相关性')
  36. # 创建累积和图,位于(2,0),跨越1行4列
  37. ax_cumsum = plt.subplot2grid((4, 4), (2, 0), colspan=4)
  38. ax_cumsum.plot(y3)
  39. ax_cumsum.set_title('累积和')
  40. # 创建直方图,位于(3,0),跨越1行2列
  41. ax_hist = plt.subplot2grid((4, 4), (3, 0), colspan=2)
  42. ax_hist.hist(data.flatten(), bins=20)
  43. ax_hist.set_title('数据分布')
  44. # 创建表格,位于(3,2),跨越1行2列
  45. ax_table = plt.subplot2grid((4, 4), (3, 2), colspan=2)
  46. ax_table.axis('off')
  47. table_data = [
  48.     ['统计量', '值'],
  49.     ['平均值', f'{np.mean(data):.2f}'],
  50.     ['标准差', f'{np.std(data):.2f}'],
  51.     ['最小值', f'{np.min(data):.2f}'],
  52.     ['最大值', f'{np.max(data):.2f}']
  53. ]
  54. table = ax_table.table(cellText=table_data, loc='center')
  55. table.auto_set_font_size(False)
  56. table.set_fontsize(10)
  57. ax_table.set_title('数据摘要')
  58. # 调整子图间距
  59. plt.tight_layout(rect=[0, 0, 1, 0.96])  # 为标题留出空间
  60. # 显示图形
  61. plt.show()
复制代码

嵌套图表和复杂布局

有时,我们需要在一个子图中创建另一个子图,或者创建更复杂的布局。Matplotlib提供了几种方法来实现这一点。

使用inset_axes创建嵌套子图

inset_axes方法允许我们在一个现有的子图中创建一个嵌套的子图。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  4. # 创建数据
  5. x = np.linspace(0, 10, 1000)
  6. y = np.sin(x) * np.exp(-x/10)
  7. # 创建图形
  8. fig, ax = plt.subplots(figsize=(10, 6))
  9. # 绘制主图
  10. ax.plot(x, y)
  11. ax.set_title('阻尼振荡')
  12. ax.set_xlabel('x')
  13. ax.set_ylabel('y')
  14. # 创建嵌套子图
  15. axins = inset_axes(ax, width="40%", height="30%", loc='upper right', borderpad=2)
  16. axins.plot(x, y)
  17. axins.set_xlim(0, 2)
  18. axins.set_ylim(0.9, 1.0)
  19. axins.set_title('放大视图')
  20. # 添加连接线
  21. from mpl_toolkits.axes_grid1.inset_locator import mark_inset
  22. mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
  23. # 显示图形
  24. plt.show()
复制代码

使用make_axes_locatable创建颜色条

make_axes_locatable是一个有用的工具,可以创建与主图对齐的颜色条。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from mpl_toolkits.axes_grid1 import make_axes_locatable
  4. # 创建数据
  5. x = np.linspace(-3, 3, 100)
  6. y = np.linspace(-3, 3, 100)
  7. X, Y = np.meshgrid(x, y)
  8. Z = np.exp(-(X**2 + Y**2))
  9. # 创建图形
  10. fig, ax = plt.subplots(figsize=(8, 6))
  11. # 绘制等高线图
  12. c = ax.contourf(X, Y, Z, levels=20, cmap='viridis')
  13. ax.set_title('二维高斯分布')
  14. # 创建颜色条
  15. divider = make_axes_locatable(ax)
  16. cax = divider.append_axes("right", size="5%", pad=0.1)
  17. plt.colorbar(c, cax=cax)
  18. # 显示图形
  19. plt.show()
复制代码

创建复杂的嵌套布局

我们可以结合使用多种技术来创建非常复杂的嵌套布局。
  1. import matplotlib.pyplot as plt
  2. import matplotlib.gridspec as gridspec
  3. import numpy as np
  4. from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  5. # 创建数据
  6. x = np.linspace(0, 10, 100)
  7. y1 = np.sin(x)
  8. y2 = np.cos(x)
  9. y3 = np.tan(x)
  10. y4 = np.exp(x/10)
  11. data = np.random.randn(100, 5)
  12. # 创建图形
  13. fig = plt.figure(figsize=(15, 10))
  14. fig.suptitle('复杂数据分析仪表板', fontsize=16)
  15. # 创建主GridSpec
  16. gs = gridspec.GridSpec(3, 3)
  17. # 创建大子图,跨越前两行的两列
  18. ax_main = fig.add_subplot(gs[:2, :2])
  19. ax_main.plot(x, y1, label='正弦函数')
  20. ax_main.plot(x, y2, label='余弦函数')
  21. ax_main.set_title('主要趋势')
  22. ax_main.legend()
  23. # 在大子图中创建嵌套子图
  24. ax_inset = inset_axes(ax_main, width="30%", height="30%", loc='lower right')
  25. ax_inset.plot(x, y3)
  26. ax_inset.set_title('正切函数')
  27. ax_inset.set_ylim(-5, 5)
  28. # 创建右上角的子图
  29. ax_top_right = fig.add_subplot(gs[0, 2])
  30. ax_top_right.bar(range(5), np.mean(data, axis=0))
  31. ax_top_right.set_title('平均值')
  32. # 创建中右角的子图
  33. ax_middle_right = fig.add_subplot(gs[1, 2])
  34. ax_middle_right.boxplot(data)
  35. ax_middle_right.set_title('数据分布')
  36. # 创建底部的子图,跨越第三行的三列
  37. ax_bottom = fig.add_subplot(gs[2, :])
  38. ax_bottom.plot(x, y4)
  39. ax_bottom.set_title('指数函数')
  40. # 在底部子图中创建嵌套子图
  41. ax_bottom_inset = inset_axes(ax_bottom, width="30%", height="40%", loc='center left')
  42. ax_bottom_inset.hist(np.random.randn(1000), bins=20)
  43. ax_bottom_inset.set_title('正态分布')
  44. # 调整子图间距
  45. plt.tight_layout(rect=[0, 0, 1, 0.96])  # 为标题留出空间
  46. # 显示图形
  47. plt.show()
复制代码

调整子图间距和大小

在创建多个子图时,调整它们之间的间距和大小是非常重要的,这可以使图形更加美观和易读。

使用tight_layout自动调整

tight_layout函数可以自动调整子图参数,以避免标签重叠。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建2x2的网格
  10. fig, axes = plt.subplots(2, 2, figsize=(10, 8))
  11. # 绘制子图
  12. axes[0, 0].plot(x, y1)
  13. axes[0, 0].set_title('正弦函数')
  14. axes[0, 0].set_xlabel('x')
  15. axes[0, 0].set_ylabel('sin(x)')
  16. axes[0, 1].plot(x, y2)
  17. axes[0, 1].set_title('余弦函数')
  18. axes[0, 1].set_xlabel('x')
  19. axes[0, 1].set_ylabel('cos(x)')
  20. axes[1, 0].plot(x, y3)
  21. axes[1, 0].set_title('正切函数')
  22. axes[1, 0].set_xlabel('x')
  23. axes[1, 0].set_ylabel('tan(x)')
  24. axes[1, 0].set_ylim(-5, 5)
  25. axes[1, 1].plot(x, y4)
  26. axes[1, 1].set_title('指数函数')
  27. axes[1, 1].set_xlabel('x')
  28. axes[1, 1].set_ylabel('exp(x/10)')
  29. # 自动调整子图间距
  30. plt.tight_layout()
  31. # 显示图形
  32. plt.show()
复制代码

使用subplots_adjust手动调整

subplots_adjust函数允许我们手动调整子图之间的间距。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建2x2的网格
  10. fig, axes = plt.subplots(2, 2, figsize=(10, 8))
  11. # 绘制子图
  12. axes[0, 0].plot(x, y1)
  13. axes[0, 0].set_title('正弦函数')
  14. axes[0, 0].set_xlabel('x')
  15. axes[0, 0].set_ylabel('sin(x)')
  16. axes[0, 1].plot(x, y2)
  17. axes[0, 1].set_title('余弦函数')
  18. axes[0, 1].set_xlabel('x')
  19. axes[0, 1].set_ylabel('cos(x)')
  20. axes[1, 0].plot(x, y3)
  21. axes[1, 0].set_title('正切函数')
  22. axes[1, 0].set_xlabel('x')
  23. axes[1, 0].set_ylabel('tan(x)')
  24. axes[1, 0].set_ylim(-5, 5)
  25. axes[1, 1].plot(x, y4)
  26. axes[1, 1].set_title('指数函数')
  27. axes[1, 1].set_xlabel('x')
  28. axes[1, 1].set_ylabel('exp(x/10)')
  29. # 手动调整子图间距
  30. plt.subplots_adjust(
  31.     left=0.1,    # 左边界
  32.     right=0.9,   # 右边界
  33.     bottom=0.1,  # 下边界
  34.     top=0.9,     # 上边界
  35.     wspace=0.4,  # 水平间距
  36.     hspace=0.4   # 垂直间距
  37. )
  38. # 显示图形
  39. plt.show()
复制代码

使用constrained_layout进行高级布局控制

constrained_layout是Matplotlib 2.2版本引入的新功能,它提供了更高级的布局控制。
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 创建数据
  4. x = np.linspace(0, 10, 100)
  5. y1 = np.sin(x)
  6. y2 = np.cos(x)
  7. y3 = np.tan(x)
  8. y4 = np.exp(x/10)
  9. # 创建图形,启用constrained_layout
  10. fig, axes = plt.subplots(2, 2, figsize=(10, 8), constrained_layout=True)
  11. # 绘制子图
  12. axes[0, 0].plot(x, y1)
  13. axes[0, 0].set_title('正弦函数')
  14. axes[0, 0].set_xlabel('x')
  15. axes[0, 0].set_ylabel('sin(x)')
  16. axes[0, 1].plot(x, y2)
  17. axes[0, 1].set_title('余弦函数')
  18. axes[0, 1].set_xlabel('x')
  19. axes[0, 1].set_ylabel('cos(x)')
  20. axes[1, 0].plot(x, y3)
  21. axes[1, 0].set_title('正切函数')
  22. axes[1, 0].set_xlabel('x')
  23. axes[1, 0].set_ylabel('tan(x)')
  24. axes[1, 0].set_ylim(-5, 5)
  25. axes[1, 1].plot(x, y4)
  26. axes[1, 1].set_title('指数函数')
  27. axes[1, 1].set_xlabel('x')
  28. axes[1, 1].set_ylabel('exp(x/10)')
  29. # 设置constrained_layout参数
  30. fig.set_constrained_layout_pads(
  31.     w_pad=0.2,  # 水平间距
  32.     h_pad=0.2,  # 垂直间距
  33.     wspace=0.2,  # 子图间水平间距
  34.     hspace=0.2   # 子图间垂直间距
  35. )
  36. # 显示图形
  37. plt.show()
复制代码

实际案例:创建专业仪表板

让我们通过一个实际案例,综合运用前面学到的技巧,创建一个专业的数据分析仪表板。
  1. import matplotlib.pyplot as plt
  2. import matplotlib.gridspec as gridspec
  3. import numpy as np
  4. import pandas as pd
  5. from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  6. from mpl_toolkits.axes_grid1 import make_axes_locatable
  7. # 设置随机种子以确保结果可重现
  8. np.random.seed(42)
  9. # 创建模拟数据
  10. dates = pd.date_range('2023-01-01', periods=100)
  11. values = np.cumsum(np.random.randn(100)) + 100
  12. categories = ['A', 'B', 'C', 'D', 'E']
  13. category_values = np.random.randint(10, 100, size=(100, 5))
  14. correlation_data = np.random.randn(100, 2)
  15. # 创建图形
  16. fig = plt.figure(figsize=(20, 15))
  17. fig.suptitle('业务数据分析仪表板', fontsize=20, fontweight='bold')
  18. # 创建主GridSpec
  19. gs = gridspec.GridSpec(4, 4, figure=fig)
  20. # 1. 创建主趋势图(跨越前两行的前两列)
  21. ax_main = fig.add_subplot(gs[0:2, 0:2])
  22. ax_main.plot(dates, values, linewidth=2, color='#1f77b4')
  23. ax_main.set_title('主要业务指标趋势', fontsize=14, fontweight='bold')
  24. ax_main.set_xlabel('日期')
  25. ax_main.set_ylabel('指标值')
  26. ax_main.grid(True, linestyle='--', alpha=0.7)
  27. # 在主趋势图中添加嵌套图,显示最近30天的详细数据
  28. ax_inset = inset_axes(ax_main, width="40%", height="30%", loc='upper right', borderpad=2)
  29. ax_inset.plot(dates[-30:], values[-30:], linewidth=2, color='#ff7f0e')
  30. ax_inset.set_title('最近30天', fontsize=10)
  31. ax_inset.grid(True, linestyle='--', alpha=0.7)
  32. # 2. 创建分类柱状图(位于第一行第三列)
  33. ax_bar = fig.add_subplot(gs[0, 2])
  34. bar_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
  35. ax_bar.bar(categories, np.mean(category_values, axis=0), color=bar_colors)
  36. ax_bar.set_title('各分类平均值', fontsize=14, fontweight='bold')
  37. ax_bar.set_xlabel('分类')
  38. ax_bar.set_ylabel('平均值')
  39. # 3. 创建饼图(位于第一行第四列)
  40. ax_pie = fig.add_subplot(gs[0, 3])
  41. pie_data = np.mean(category_values, axis=0)
  42. ax_pie.pie(pie_data, labels=categories, autopct='%1.1f%%', colors=bar_colors)
  43. ax_pie.set_title('分类占比', fontsize=14, fontweight='bold')
  44. # 4. 创建箱线图(位于第二行第三列)
  45. ax_box = fig.add_subplot(gs[1, 2])
  46. ax_box.boxplot(category_values, labels=categories)
  47. ax_box.set_title('分类数据分布', fontsize=14, fontweight='bold')
  48. ax_box.set_xlabel('分类')
  49. ax_box.set_ylabel('值')
  50. # 5. 创建散点图(位于第二行第四列)
  51. ax_scatter = fig.add_subplot(gs[1, 3])
  52. ax_scatter.scatter(correlation_data[:, 0], correlation_data[:, 1], alpha=0.6)
  53. ax_scatter.set_title('相关性分析', fontsize=14, fontweight='bold')
  54. ax_scatter.set_xlabel('变量1')
  55. ax_scatter.set_ylabel('变量2')
  56. # 6. 创建分类趋势图(跨越第三行的前两列)
  57. ax_category = fig.add_subplot(gs[2, 0:2])
  58. for i, cat in enumerate(categories):
  59.     ax_category.plot(dates, category_values[:, i], label=cat, color=bar_colors[i])
  60. ax_category.set_title('各分类趋势', fontsize=14, fontweight='bold')
  61. ax_category.set_xlabel('日期')
  62. ax_category.set_ylabel('值')
  63. ax_category.legend()
  64. ax_category.grid(True, linestyle='--', alpha=0.7)
  65. # 7. 创建热力图(位于第三行第三列)
  66. ax_heatmap = fig.add_subplot(gs[2, 2])
  67. heatmap_data = np.corrcoef(category_values.T)
  68. im = ax_heatmap.imshow(heatmap_data, cmap='coolwarm')
  69. ax_heatmap.set_title('分类相关性', fontsize=14, fontweight='bold')
  70. ax_heatmap.set_xticks(np.arange(len(categories)))
  71. ax_heatmap.set_yticks(np.arange(len(categories)))
  72. ax_heatmap.set_xticklabels(categories)
  73. ax_heatmap.set_yticklabels(categories)
  74. # 添加颜色条
  75. divider = make_axes_locatable(ax_heatmap)
  76. cax = divider.append_axes("right", size="5%", pad=0.1)
  77. plt.colorbar(im, cax=cax)
  78. # 8. 创建面积图(位于第三行第四列)
  79. ax_area = fig.add_subplot(gs[2, 3])
  80. ax_area.stackplot(dates, category_values.T, labels=categories, colors=bar_colors, alpha=0.7)
  81. ax_area.set_title('分类累积', fontsize=14, fontweight='bold')
  82. ax_area.set_xlabel('日期')
  83. ax_area.set_ylabel('累积值')
  84. ax_area.legend(loc='upper left')
  85. # 9. 创建数据摘要表(跨越第四行的四列)
  86. ax_table = fig.add_subplot(gs[3, :])
  87. ax_table.axis('off')
  88. # 计算统计数据
  89. stats = []
  90. for i, cat in enumerate(categories):
  91.     stats.append([
  92.         cat,
  93.         f'{np.mean(category_values[:, i]):.2f}',
  94.         f'{np.std(category_values[:, i]):.2f}',
  95.         f'{np.min(category_values[:, i]):.2f}',
  96.         f'{np.max(category_values[:, i]):.2f}',
  97.         f'{np.median(category_values[:, i]):.2f}'
  98.     ])
  99. # 创建表格
  100. table_data = [['分类', '平均值', '标准差', '最小值', '最大值', '中位数']] + stats
  101. table = ax_table.table(
  102.     cellText=table_data,
  103.     cellLoc='center',
  104.     loc='center',
  105.     colColours=['#f3f3f3']*6
  106. )
  107. table.auto_set_font_size(False)
  108. table.set_fontsize(12)
  109. table.scale(1, 1.5)
  110. # 设置表格样式
  111. for i in range(len(table_data[0])):
  112.     table[(0, i)].set_facecolor('#4bacc6')
  113.     table[(0, i)].set_text_props(weight='bold', color='white')
  114. for i in range(1, len(table_data)):
  115.     for j in range(len(table_data[0])):
  116.         if i % 2 == 0:
  117.             table[(i, j)].set_facecolor('#f3f3f3')
  118. ax_table.set_title('数据摘要统计', fontsize=14, fontweight='bold', pad=20)
  119. # 调整布局
  120. plt.tight_layout(rect=[0, 0, 1, 0.96])  # 为标题留出空间
  121. # 保存图形
  122. plt.savefig('business_dashboard.png', dpi=300, bbox_inches='tight')
  123. # 显示图形
  124. plt.show()
复制代码

这个仪表板展示了多种类型的图表,包括趋势图、柱状图、饼图、箱线图、散点图、热力图、面积图和表格,它们共同构成了一个全面的数据分析视图。通过使用GridSpec和嵌套布局,我们能够创建一个结构清晰、信息丰富的专业仪表板。

最佳实践和技巧总结

在使用Matplotlib创建网格化图表布局时,以下最佳实践和技巧可以帮助你提高效率和创建更专业的可视化作品:

1. 选择合适的布局方法

• 简单规则网格:使用plt.subplots(),它简单直观,适合创建规则的网格布局。
• 不规则网格:使用subplot2grid,它比GridSpec更简单,但仍然提供了很大的灵活性。
• 复杂布局:使用GridSpec,它提供了最灵活的控制,适合创建复杂的、不规则的网格布局。
• 嵌套图表:使用inset_axes,它允许你在现有的子图中创建嵌套的子图。

2. 合理设置图形大小
  1. # 根据子图数量和复杂性设置合适的图形大小
  2. fig, axes = plt.subplots(2, 3, figsize=(15, 10))  # 宽15英寸,高10英寸
复制代码

3. 使用共享轴提高可比性
  1. # 共享x轴和y轴,使子图之间的比较更加直观
  2. fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True, sharey=True)
复制代码

4. 调整子图间距
  1. # 使用tight_layout自动调整子图间距
  2. plt.tight_layout()
  3. # 或者使用subplots_adjust手动调整
  4. plt.subplots_adjust(
  5.     left=0.1,    # 左边界
  6.     right=0.9,   # 右边界
  7.     bottom=0.1,  # 下边界
  8.     top=0.9,     # 上边界
  9.     wspace=0.4,  # 水平间距
  10.     hspace=0.4   # 垂直间距
  11. )
复制代码

5. 使用一致的样式和颜色
  1. # 定义颜色方案
  2. colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']
  3. # 在所有子图中使用相同的样式
  4. for ax, color in zip(axes.flat, colors):
  5.     ax.plot(x, y, color=color, linewidth=2)
  6.     ax.grid(True, linestyle='--', alpha=0.7)
复制代码

6. 添加适当的标题和标签
  1. # 为每个子图添加描述性标题和标签
  2. ax.set_title('销售趋势', fontsize=12, fontweight='bold')
  3. ax.set_xlabel('日期')
  4. ax.set_ylabel('销售额')
复制代码

7. 使用图例说明数据系列
  1. # 添加图例,并设置位置
  2. ax.plot(x, y1, label='产品A')
  3. ax.plot(x, y2, label='产品B')
  4. ax.legend(loc='upper right')
复制代码

8. 考虑数据密度和比例
  1. # 对于数据密度高的区域,使用嵌套图进行放大显示
  2. ax_inset = inset_axes(ax, width="40%", height="30%", loc='upper right')
  3. ax_inset.plot(x_zoom, y_zoom)
复制代码

9. 添加网格线提高可读性
  1. # 添加网格线,并设置样式
  2. ax.grid(True, linestyle='--', alpha=0.7)
复制代码

10. 保存高质量图形
  1. # 保存高分辨率图形,适合打印或出版
  2. plt.savefig('visualization.png', dpi=300, bbox_inches='tight')
复制代码

11. 使用面向对象的API
  1. # 使用面向对象的API,而不是pyplot的状态机接口
  2. fig, ax = plt.subplots()
  3. ax.plot(x, y)  # 而不是 plt.plot(x, y)
复制代码

12. 创建可重用的函数
  1. def create_dashboard(data, figsize=(15, 10)):
  2.     """创建数据分析仪表板"""
  3.     fig = plt.figure(figsize=figsize)
  4.     gs = gridspec.GridSpec(3, 3)
  5.    
  6.     # 创建子图
  7.     ax1 = fig.add_subplot(gs[0, :2])
  8.     ax2 = fig.add_subplot(gs[0, 2])
  9.     # ... 更多子图
  10.    
  11.     # 绘制数据
  12.     ax1.plot(data['dates'], data['values'])
  13.     # ... 更多绘图代码
  14.    
  15.     # 调整布局
  16.     plt.tight_layout()
  17.    
  18.     return fig
  19. # 使用函数
  20. fig = create_dashboard(data)
  21. plt.show()
复制代码

通过遵循这些最佳实践和技巧,你可以创建出专业、美观且信息丰富的数据可视化作品,大幅提升你的数据分析效率和展示效果。

结论

Matplotlib提供了多种创建网格化图表布局的方法,从简单的subplot到高级的GridSpec,每种方法都有其适用的场景。通过掌握这些技巧,你可以轻松创建专业的数据可视化作品,不仅能够更有效地分析数据,还能更清晰地传达你的发现。

在实际应用中,选择合适的布局方法、合理设置图形大小、调整子图间距、使用一致的样式和颜色、添加适当的标题和标签等,都是创建高质量可视化作品的关键。通过不断实践和探索,你将能够熟练运用Matplotlib的网格化布局技巧,创建出令人印象深刻的数据可视化作品。

希望本文能够帮助你更好地理解和掌握Matplotlib的网格化图表布局技巧,从而在数据分析、科学研究和商业报告中创建出更加专业和有效的可视化作品。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则

关闭

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

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

Powered by Pixtech

© 2025-2026 Pixtech Team.

>