简体   繁体   English

如何保存 nltk FreqDist 图?

[英]How to save a nltk FreqDist plot?

I've tried different methods to save my plot but every thing I've tried has turned up with a blank image and I'm not currently out of ideas.我尝试了不同的方法来保存我的情节,但是我尝试过的每件事都出现了空白图像,而且我目前还没有失去想法。 Any help with other suggestions that could fix this?对可以解决此问题的其他建议有什么帮助吗? The code sample is below.代码示例如下。

word_frequency = nltk.FreqDist(merged_lemmatizedTokens) #obtains frequency distribution for each token
print("\nMost frequent top-10 words: ", word_frequency.most_common(10))
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')

I was able to save the NLTK FreqDist plot, when I first initialized a figure object, then called the plot function and finally saved the figure object.我能够保存 NLTK FreqDist 图,当我第一次初始化图形对象时,然后调用绘图函数,最后保存图形对象。

import matplotlib.pyplot as plt
from nltk.probability import FreqDist

fig = plt.figure(figsize = (10,4))
plt.gcf().subplots_adjust(bottom=0.15) # to avoid x-ticks cut-off
fdist = FreqDist(merged_lemmatizedTokens)
fdist.plot(10, cumulative=False)
plt.show()
fig.savefig('freqDist.png', bbox_inches = "tight")

I think you can try the following:我认为您可以尝试以下操作:

plt.ion()
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
plt.ioff()
plt.show()

This is because inside nltk's plot function, plt.show() is called and once the figure is closed, plt.savefig() has no active figure to save anymore.这是因为在 nltk 的plot函数中, plt.show()被调用,一旦图形关闭, plt.savefig()就没有活动图形要保存了。

The workaround is to turn interactive mode on, such that the plt.show() from inside the nltk function does not block.解决方法是打开交互模式,这样 nltk 函数内部的 plt.show plt.show()就不会阻塞。 Then savefig is called with a current figure available and saves the correct plot.然后使用可用的当前图形调用 savefig 并保存正确的绘图。 To then show the figure, interactive mode needs to be turned off again and plt.show() be called externally - this time in a blocking mode.然后显示该图,需要再次关闭交互模式并在外部调用plt.show() - 这次是在阻塞模式下。

Ideally, nltk would rewrite their plotting function to either allow to set the blocking status, or to not show the plot and return the created figure, or to take a Axes as input to which to plot.理想情况下, nltk将重写它们的绘图函数,以允许设置阻塞状态,或者不show绘图并返回创建的图形,或者将Axes作为要绘制的输入。 Feel free to reach out to them with this request.请随时通过此请求与他们联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM