您现在的位置是:首页 > 技术教程 正文

matplotlib多图合一的四种实现(多张图显示在一个figure中)

admin 阅读: 2024-03-24
后台-插件-广告管理-内容页头部广告(手机)

文章目录

  • Subplot多合一显示
    • 1 plt.subplot
    • 2 plt.subplot2grid
    • 3 gridspec.GridSpec
    • 4 plt.subplots

Subplot多合一显示

1 plt.subplot

使用plt.subplot(rownum, columnnum, index)说明新图纸是几行几列的

import matplotlib.pyplot as plt plt.figure() plt.subplot(2, 2, 1) plt.plot([0, 1], [0, 1]) plt.subplot(2, 2, 2) plt.plot([0, 1], [0, 1]) plt.subplot(2, 1, 2) plt.plot([0, 1], [0, 1]) plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

image-20230112154912308

2 plt.subplot2grid

使用plt.subplot2grid(总格数, 起始格数, rowspan, colspan)来绘制

import matplotlib.pyplot as plt plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) ax1.plot([1, 2], [1, 2]) # 设置某属性的时候需要在前面加set_ ax1.set_title("ax1 title") ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) ax4 = plt.subplot2grid((3, 3), (2, 0)) ax5 = plt.subplot2grid((3, 3), (2, 1)) plt.tight_layout() plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

image-20230112160001950

3 gridspec.GridSpec

首先使用gridspec.GridSpec(rownum, colnum)声明将figure分割成几块,然后在绘图时使用切片声明使用哪几块即可

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure() gs = gridspec.GridSpec(3, 3) ax1 = plt.subplot(gs[0, :]) ax2 = plt.subplot(gs[1, :2]) ax3 = plt.subplot(gs[1:, 2]) ax4 = plt.subplot(gs[2, 0]) ax5 = plt.subplot(gs[2, 1]) plt.tight_layout() plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

image-20230112160140602

4 plt.subplots

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True) ax11.plot([1, 2], [1, 2]) plt.tight_layout() plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

image-20230112160457523

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索