簡體   English   中英

在Python中使用Matplotlib如何檢查子圖中的子圖是否為空

[英]In Python with Matplotlib how to check if a subplot is empty in the figure

我有一些使用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循環結構實際上只是一個占位符,可以舉例說明如何交換軸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM