我用NetworkX创建了一些图形,并用Matplotlib在屏幕上显示它们。具体地说,由于我不知道需要显示多少个图,所以我会动态地在图上创建一个subplot。那很好。但是,在脚本的某个点上,一些subplots从图中删除,并且图中显示了一些空的子块。我想避免它,但我无法检索图中空的子块。这是我的代码:

#instantiate a figure with size 12x12
fig = plt.figure(figsize=(12,12))

#when a graph is created, also a subplot is created:
ax = plt.subplot(3,4,count+1)

#and the graph is drawn inside it: N.B.: pe is the graph to be shown
nx.draw(pe, positions, labels=positions, font_size=8, font_weight='bold', node_color='yellow', alpha=0.5)

#many of them are created..

#under some conditions a subplot needs to be deleted, and so..
#condition here....and then retrieve the subplot to deleted. The graph contains the id of the ax in which it is shown.
for ax in fig.axes:
    if id(ax) == G.node[shape]['idax']:
         fig.delaxes(ax)

直到这里工作正常,但是当我显示这个数字时,结果看起来是这样的:
你可以注意到那里有两个空的子块。。在第二个位置和第五个位置。我怎样才能避免呢?或者。。如何重新组织子块,使图中不再有空白?
任何帮助都是值得的!提前谢谢。

最佳答案

为此,我会保留一个坐标轴列表,当我删除其中一个坐标轴的内容时,我会用一个完整的坐标轴来交换它。我认为下面的例子解决了这个问题(或者至少给出了解决问题的方法):

import matplotlib.pyplot as plt

# this is just a helper class to keep things clean
class MyAxis(object):
    def __init__(self,ax,fig):
        # this flag tells me if there is a plot in these axes
        self.empty = False
        self.ax = ax
        self.fig = fig
        self.pos = self.ax.get_position()

    def del_ax(self):
        # delete the axes
        self.empty = True
        self.fig.delaxes(self.ax)

    def swap(self,other):
        # swap the positions of two axes
        #
        # THIS IS THE IMPORTANT BIT!
        #
        new_pos = other.ax.get_position()
        self.ax.set_position(new_pos)
        other.ax.set_position(self.pos)
        self.pos = new_pos

def main():
    # generate a figure and 10 subplots in a grid
    fig, axes = plt.subplots(ncols=5,nrows=2)

    # get these as a list of MyAxis objects
    my_axes = [MyAxis(ax,fig) for ax in axes.ravel()]

    for ax in my_axes:
        # plot some random stuff
        ax.ax.plot(range(10))

    # delete a couple of axes
    my_axes[0].del_ax()
    my_axes[6].del_ax()

    # count how many axes are dead
    dead = sum([ax.empty for ax in my_axes])

    # swap the dead plots for full plots in a row wise fashion
    for kk in range(dead):
        for ii,ax1 in enumerate(my_axes[kk:]):
            if ax1.empty:
                print ii,"dead"
                for jj,ax2 in enumerate(my_axes[::-1][kk:]):
                    if not ax2.empty:
                        print "replace with",jj
                        ax1.swap(ax2)
                        break
                break



    plt.draw()
    plt.show()

if __name__ == "__main__":
    main()

极为丑陋的for循环构造实际上只是一个占位符,用于举例说明如何交换轴。

关于python - 在具有Matplotlib的Python中,如何检查图中的子图是否为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22932904/

10-12 21:25