【问题标题】:Matplotlib and networkx merging Graphs when drawingMatplotlib和networkx在绘制时合并Graphs
【发布时间】:2016-09-20 08:18:20
【问题描述】:

我正在使用Networkx 使用以下代码可视化一些图表:

import networkx as nx
import matplotlib.pyplot as plt

def drawgraph(g, filename):
    #plt.figure() I had to comment this line because it gives me an 'alloc: invalid block` error
    nx.draw(g)
    plt.draw() # I added this hoping it might solve the problem (outlined in the text below the code)
    plt.savefig(filename)
   #plt.show() this solves the problem, however it's blocking call and I'm drawing hundreds of graphs

现在的问题是,随后对drawgraph 的调用将导致绘制的图形与之前的图形合并,例如:如果我调用它两次,第一个绘制正确,但第二张图片包含第一个图形除了第二个图表。在函数末尾放置一个plt.show() 可以解决问题,但是这是一个阻塞调用,我不能这样做。那么我该如何解决这个问题呢?

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    所以在环顾四周后,我找到了答案,我取消了plt.figure() 行的注释,并在末尾添加了一个plt.close() 调用:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    def drawgraph(g, filename):
        plt.figure()
        nx.draw(g)
        plt.draw() 
        plt.savefig(filename)
        plt.close()
    

    【讨论】:

      【解决方案2】:

      任何时候你用matplotlib.pyplot 绘制一些东西然后再次绘制一些东西,这两个东西都会出现。您需要关闭或清除该图。

      添加plt.clf()清图即可解决问题。我不相信plt.draw() 会为你做任何事情。

      【讨论】:

        猜你喜欢
        • 2015-12-15
        • 2018-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-13
        • 1970-01-01
        相关资源
        最近更新 更多