I try to generate two separate wordcloud for positive and negative. However, when I use savefig it only save the last figure. The last figure is negative sentiment.
TEXT_COLUMN = 'pre_process'
TARGET_COLUMN = 'label'
# visualize the data on a WordCloud
def visualize(label):
words = ''
for msg in data[data[TARGET_COLUMN] == label][TEXT_COLUMN]:
msg = msg.lower()
words += msg + ' '
wordcloud = WordCloud(width=600, height=600).generate(words)
plt.imshow(wordcloud)
plt.axis('off')
plt.title('Wordcloud')
plt.savefig('static/airasia_negcloud.png',transparent=True)
plt.show()
plt.clf()
# display wordcloud
visualize(1)
visualize(0)
Here is my wordcloud coding. When I visualize it, it display correctly on PyCharm but in the folder, one is blank image which is suppose to be positive wordcloud and another one is negative worcloud.
The issue you are facing is because you are using the same file name ('static/airasia_negcloud.png'
) to save both of your wordclouds
, so only the last one is being saved. To solve this issue, you can either use a different file name for each of the wordclouds
or overwrite the file every time you call plt.savefig()
. To use a different file name, you can add the label to the file name like this:
plt.savefig('static/airasia_{}cloud.png'.format('pos' if label == 0 else 'neg'),transparent=True)
Or, to overwrite the file, you can add the line plt.clf()
before the call to plt.savefig()
, which will clear the current figure:
def visualize(label):
words = ''
for msg in data[data[TARGET_COLUMN] == label][TEXT_COLUMN]:
msg = msg.lower()
words += msg + ' '
wordcloud = WordCloud(width=600, height=600).generate(words)
plt.imshow(wordcloud)
plt.axis('off')
plt.title('Wordcloud')
plt.savefig('static/airasia_negcloud.png',transparent=True)
plt.show()
plt.clf()