我已经尝试了不同的方法来保存我的图,但我尝试的每一件事都出现了空白图像,我目前并没有失去想法。有没有其他可以解决这个问题的建议?代码示例如下所示。
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')发布于 2019-10-14 04:25:58
当我第一次初始化figure对象,然后调用FreqDist函数,最后保存figure对象时,我能够保存NLTK plot绘图。
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")发布于 2018-10-21 02:14:40
我认为你可以尝试以下方法:
plt.ion()
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
plt.ioff()
plt.show()这是因为在nltk的plot函数中调用了plt.show(),一旦图形关闭,plt.savefig()就没有活动的图形可以保存了。
解决方法是打开交互模式,以便来自nltk函数内部的plt.show()不会阻塞。然后使用当前可用图形调用savefig,并保存正确的图。为了显示该图,需要再次关闭交互模式,并在外部调用plt.show() --这次是在阻塞模式下。
理想情况下,nltk会重写它们的绘图函数,允许设置阻塞状态,或者不对绘图执行show操作并返回创建的图形,或者将Axes作为绘图的输入。请随时向他们提出这个请求。
https://stackoverflow.com/questions/52908305
复制相似问题