Pycharm和matplotlib只在调试模式下工作

4
我在Pycharm 2017.3.3 Community Edition中遇到了一个奇怪的问题。我正在编写一个循环,每次迭代都应该显示不同的图形。当我运行代码时,只有第一张图显示出来,程序就会卡住。如果我在没有断点的情况下以调试模式运行代码,情况也是一样的。然而,如果我设置一个断点,并在达到断点时继续执行程序,所有的图形都会显示出来,程序可以成功执行。还想澄清一下,我之前用过这段代码,只有少量图形时运行良好。
以下是代码:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.externals import joblib

feat_file = 'C:\\Users\\DianaCarolina\\Google Drive\\Maestría\\datos\\indices_Diana\\all_type.xlsx'
sites = {"Bosque":['5256', '5260'], "Rastrojo": ['5253', '5255'], "Pastizal": ['5257', '7125']}
model=joblib.load("C:\\Users\\DianaCarolina\\Google Drive\\Maestría\\datos\\indices_Diana\\ecotyhmm13_3.pkl")
nclasses = 13
for comp in range(nclasses):
    histData = []
    types = []
    col = []
    for type in sites:
        df = pd.read_excel(feat_file, sheet_name=type, index_col=0)
        mdata=df.loc[df.iloc[:, 20] == comp, "Mes"]
        types.append(type)
        histData.append(mdata)

        if len(col) < 3:
            if type == "Bosque" and "green" not in col:
                col.append("green")
            elif type == "Rastrojo" and "orange" not in col:
                col.append("orange")
            elif type == "Pastizal" and "yellow" not in col:
                col.append("yellow")

    mclass = np.sum(np.array([model.gmms_[comp].weights_]).T * model.gmms_[comp].means_, 0)

    plt.figure()

    if not histData[0].empty or not histData[1].empty or not histData[2].empty:
        plt.subplot(2, 1, 1)
        n, bins, patches = plt.hist(histData, np.arange(0.5,13, 1), stacked=True, label= types, color = col, rwidth=0.8)
        plt.legend()
        plt.xticks(range(1,13), ("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", \
                                      "Septiembre", "Octubre", "Noviembre", "Diciembre"))
        plt.title("Clase "+str(comp+1)+" de "+str(nclasses))

        plt.subplot(2, 1, 2)

    plt.stem(mclass)
    plt.xticks(range(14), list(df.loc[:, "M":"Salida2_4"]))
    plt.title("Medias de características para la clase")
    plt.show()

你的循环语句执行了多少次? - Frank AK
@FrankAK应该显示13个数字。 - dduque
你能把你的截图放在这里吗? - Frank AK
@DavidG 好的,虽然有点长。 - dduque
1
如果你的代码非常长,将其缩减为一个 MCVE 是获得良好答案的最佳方式。 - DavidG
显示剩余7条评论
1个回答

3

plt.show() 通常只应在代码的末尾调用一次。这将显示已创建的所有图形,并且它会阻塞其后的任何代码的执行。

例如:

import matplotlib.pyplot as plt

for i in range(2):
    plt.figure()
    plt.plot([1,2,3])

    plt.show()

只有在关闭第一个图之后,才会显示第二个图。

最简单的解决方案是取消缩进plt.show(),这样一旦所有图都创建好了,它们就会全部显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接