函数仅在第二次时才在 `hist` 函数中完成执行
Function does not finish executing in `hist` function only on second time
在 Python DataFrame 中,我尝试生成直方图,它是在调用函数时第一次生成的。但是,当 create_histogram
函数被第二次调用时,它会卡在 h = df.hist(bins=3, column="amount")
处。当我说 "stuck" 时,我的意思是说它没有完成语句的执行并且执行不会继续到下一行但同时它不会给出任何错误或从执行中中断。这里到底是什么问题,我该如何解决?
import matplotlib.pyplot as plt
...
...
def create_histogram(self, field):
df = self.main_df # This is DataFrame
h = df.hist(bins=20, column="amount")
fileContent = StringIO()
plt.savefig(fileContent, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format="png",
transparent=False, bbox_inches=None, pad_inches=0.5,
frameon=None)
content = fileContent.getvalue()
return content
最后我自己弄明白了。
每当我执行该功能时,我总是收到以下日志消息,但由于我缺乏意识而忽略了它。
Backend TkAgg is interactive backend. Turning interactive mode on.
但后来我意识到这可能是它的 运行 在交互模式下(这不是我的目的)。所以,我发现有一种方法可以将其关闭,如下所示。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
这解决了我的问题。
注意:use
应在按此处给出的顺序导入 matplotlib
后立即调用。
在 Python DataFrame 中,我尝试生成直方图,它是在调用函数时第一次生成的。但是,当 create_histogram
函数被第二次调用时,它会卡在 h = df.hist(bins=3, column="amount")
处。当我说 "stuck" 时,我的意思是说它没有完成语句的执行并且执行不会继续到下一行但同时它不会给出任何错误或从执行中中断。这里到底是什么问题,我该如何解决?
import matplotlib.pyplot as plt
...
...
def create_histogram(self, field):
df = self.main_df # This is DataFrame
h = df.hist(bins=20, column="amount")
fileContent = StringIO()
plt.savefig(fileContent, dpi=None, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format="png",
transparent=False, bbox_inches=None, pad_inches=0.5,
frameon=None)
content = fileContent.getvalue()
return content
最后我自己弄明白了。
每当我执行该功能时,我总是收到以下日志消息,但由于我缺乏意识而忽略了它。
Backend TkAgg is interactive backend. Turning interactive mode on.
但后来我意识到这可能是它的 运行 在交互模式下(这不是我的目的)。所以,我发现有一种方法可以将其关闭,如下所示。
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
这解决了我的问题。
注意:use
应在按此处给出的顺序导入 matplotlib
后立即调用。