Matplotlib:保存图表无法正常工作,除非我在其后使用plt.show()

时间:2019-07-05 10:36:27

标签: matplotlib

我正在尝试使用Matplotlib创建和保存多个图表:

# Perfect Numbers Functions
# -------------------------
def getdivisors(n):
    "Get all divisors of a number."
    divisors = []
    for i in range(1, n+1):
        if n % i == 0:
            divisors.append(i)
    return divisors

def isperfect(divisors):
    "Sums the divisors of a number and checks if it is equal to the number."
    n = divisors.pop() # Grab the top number
    total = sum(divisors) # Sum all the divisors
    if n == total:
        return True
    else:
        return False

# Matplot!
# --------
import matplotlib.pyplot as plt

# iterate over some numbers
for i in range(2, 10):
    # get all divisors of the number
    divisors = getdivisors(i)

    # convert divisors to strings so they work as x labels
    xlabels = [str(x) for x in divisors]

    # create bar chart
    bars = plt.bar(xlabels, divisors)

    # change last bar to red if it's a perfect number
    if isperfect(divisors):
        bars[-1].set_color('r')

    # save chart
    filename = "%i.png" % i
    plt.savefig(filename)

    # show chart (must come after save)
    # plt.show()

由于某种原因,除非我在每个图表之后都运行plt.show(),否则这些图表将无法正确保存(它们看起来更通用)。但是,这意味着我必须在脚本运行时查看并关闭每个图表。

如何让matplotlib完全按照图表在plt.show()中显示的形式保存图表,而不必在每个图表之后都运行plt.show()

我确定我在这里犯了一个简单的错误,但是我不确定发生了什么。

0 个答案:

没有答案