【问题标题】:matplotlib subplot of 1:2:11:2:1 的 matplotlib 子图
【发布时间】:2020-03-02 22:11:35
【问题描述】:

我正在尝试使用以下布局绘制 A4 PDF:

  1. 1 个图表跨越 2 列
  2. 2 个图表,每个跨越 1 列
  3. 1 个图表跨越 2 列

我有以下代码:

fig = plt.figure(figsize=(8.27,11.69))
ax = fig.add_subplot(311)
ax = fig.add_subplot(323)
ax = fig.add_subplot(324)
ax = fig.add_subplot(315)

但我收到以下错误:

ValueError: num must be 1 <= num <= 3, not 5

我错过了什么?

【问题讨论】:

    标签: matplotlib layout subplot


    【解决方案1】:

    这是正确的语法:

    fig = plt.figure()
    ax = fig.add_subplot(311)
    ax = fig.add_subplot(323)
    ax = fig.add_subplot(324)
    ax = fig.add_subplot(313)
    

    但是,对于这种事情,如果您使用 GridSpec https://matplotlib.org/3.1.1/tutorials/intermediate/gridspec.html,您将获得可读性以下代码产生完全相同的输出,但(至少对我而言)更容易理解

    fig = plt.figure()
    gs = fig.add_gridspec(3, 2)
    fig.add_subplot(gs[0, :])
    fig.add_subplot(gs[1, 0])
    fig.add_subplot(gs[1, 1])
    fig.add_subplot(gs[2, :])
    

    【讨论】:

    • 为什么最后一个是3结尾?即 313
    • 因为对于底轴,您要布置一个 3 行 x 1 列的网格,而在这个网格上,底轴是第三个轴,所以 3,1,3313
    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2015-03-01
    • 2022-11-18
    相关资源
    最近更新 更多