【问题标题】:Matplotlib: Repositioning a subplot in a grid of subplotsMatplotlib:在子图网格中重新定位子图
【发布时间】:2012-09-04 12:59:06
【问题描述】:

我正在尝试制作一个包含 7 个子图的图。目前我正在绘制两列,一列有四个图,另一列有三个,即像这样:

我正在按以下方式构建这个情节:

    #! /usr/bin/env python
    import numpy as plotting
    import matplotlib
    from pylab import *
    x = np.random.rand(20)
    y = np.random.rand(20)
    fig = figure(figsize=(6.5,12))
    subplots_adjust(wspace=0.2,hspace=0.2)
    iplot = 420
    for i in range(7):
       iplot += 1
       ax = fig.add_subplot(iplot)
       ax.plot(x,y,'ko')
       ax.set_xlabel("x")
       ax.set_ylabel("y")
    savefig("subplots_example.png",bbox_inches='tight')

但是,对于发布,我认为这看起来有点难看——我想做的是将最后一个子图移到两列之间的中心。那么,调整最后一个子图的位置以使其居中的最佳方法是什么? IE。使前 6 个子图位于 3X2 网格中,最后一个子图位于两列之间的中心。如果可能的话,我希望能够保留for 循环,以便我可以简单地使用:

    if i == 6:
       # do something to reposition/centre this plot     

谢谢,

亚历克斯

【问题讨论】:

  • 必须是 3x2 网格吗?

标签: python matplotlib customization subplot


【解决方案1】:

使用带有 4x4 网格的网格规范 (doc),并让每个绘图跨 2 列,如下所示:

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(4, 4)
ax1 = plt.subplot(gs[0, 0:2])
ax2 = plt.subplot(gs[0,2:])
ax3 = plt.subplot(gs[1,0:2])
ax4 = plt.subplot(gs[1,2:])
ax5 = plt.subplot(gs[2,0:2])
ax6 = plt.subplot(gs[2,2:])
ax7 = plt.subplot(gs[3,1:3])
fig = gcf()
gs.tight_layout(fig)
ax_lst = [ax1,ax2,ax3,ax4,ax5,ax6,ax7]

【讨论】:

  • 这非常有效。您可以使用标准 matplotlib 技术控制网格之间的间距,允许标记轴等 - IE fig = plt.figure(figsize=(10,15)) 然后在调用每个子图/网格 gs.tight_layout(fig)
【解决方案2】:

如果您想保留 for 循环,您可以使用 subplot2grid 安排绘图,它允许使用 colspan 参数:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(20)
y = np.random.rand(20)
fig = plt.figure(figsize=(6.5,12))
plt.subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
    iplot += 1
    if i == 6:
        ax = plt.subplot2grid((4,8), (i//2, 2), colspan=4)
    else:
        # You can be fancy and use subplot2grid for each plot, which doesn't
        # require keeping the iplot variable:
        # ax = plt.subplot2grid((4,2), (i//2,i%2))

        # Or you can keep using add_subplot, which may be simpler:
        ax = fig.add_subplot(iplot)
    ax.plot(x,y,'ko')
    ax.set_xlabel("x")
    ax.set_ylabel("y")
plt.savefig("subplots_example.png",bbox_inches='tight')

【讨论】:

  • 居中的子图比其他子图大。生成最后一个子图时,4 列与最初的 2 列挤在同一空间中,因此如果仔细观察,居中子图的宽度等于其他子图的宽度加上两者之间间隙宽度的一半列。可以使用 GridSpec 方法解决此问题,如 tacaswell 的回答所示。
猜你喜欢
  • 1970-01-01
  • 2020-09-23
  • 2019-02-05
  • 2014-02-03
  • 2017-10-06
  • 2018-01-11
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多