Change word color using WordCloud in Python

Viewed 30539

I am using WordCloud from Python to create my word cloud. Here is my text, named tmp, contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact contact science science science science area area area die die groove groove line line nonlinearity nonlinearity damper damper press press symmetric symmetric soliton soliton cast publish node textured real deterministic car segment kinematics.

And my code for create the word cloud is shown as below:

wordcloud = WordCloud(background_color='white',max_font_size = 50).generate(tmp)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

Here is the picture I got. It's really weird right? So my questions are :

Firstly, why there are two contact in this picture?

Secondly, how can I change the default color setting to use only one specific color for all these words, say red for all words? I Googled and found there is a parameter called color_function in WordCloud. But I didn't get anything related to this.

the Picture I got

Any comments and suggestions would be welcomed! Many thanks in advance!!


Update

I just figured out for the second question.

#change the value in return to set the single color need, in hsl format.
def grey_color_func(word, font_size, position,orientation,random_state=None, **kwargs):
    return("hsl(230,100%%, %d%%)" % np.random.randint(49,51))

#create the wordcloud object
wordcloud = WordCloud(background_color='white',max_font_size = 50).generate(tmp)

#change the color setting
wordcloud.recolor(color_func = grey_color_func)

Anyone knows the answer for the second question?

2 Answers

Have you tried to add "collocations=False"? Otherwise WordCloud automatically tries to form multigrams.

wordcloud = WordCloud(background_color='white',
                      max_font_size = 50,
                      collocations=False
                      ).generate(tmp)

See also: https://stackoverflow.com/a/45094775/10220353

Related