Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

word cloud in python with customised random colour generation

I saw this function to generate a word cloud online however I am unable to figure out how to change the colour in the def_random_func. Say if I want orange, right now the code always produces a green-coloured word cloud. Here's the code:

import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS

def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = int(360.0 * 45.0 / 255.0)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(random_state.randint(60, 120)) / 255.0)

    return "hsl({}, {}%, {}%)".format(h, s, l)

file_content = open("rr.txt").read()
wordcloud = WordCloud(font_path=r'C:\Windows\Fonts\Verdana.ttf',
                      stopwords=STOPWORDS,
                      background_color='white',
                      width=1200,
                      height=1000,
                      color_func=random_color_func
                      ).generate(file_content)

plt.imshow(wordcloud)
plt.axis('off')
plt.show()
like image 586
Oshin patwa Avatar asked Dec 18 '22 08:12

Oshin patwa


1 Answers

The random_color_func() is creating colours of the same hue but with different luminosities. You just need decide which hue you want. So for orange, you could consider using a value of 21, for example:

def random_color_func(word=None, font_size=None, position=None,  orientation=None, font_path=None, random_state=None):
    h = int(360.0 * 21.0 / 255.0)
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(random_state.randint(60, 120)) / 255.0)

    return "hsl({}, {}%, {}%)".format(h, s, l)

The hue value is in the range 0-360, you can use an online colour picker to find a suitable value (try Googling colour picker for example). The code is just converting from the range 0-255 which is another common standard. So rather than convert, you could just make h = 30.

This would give you something like:

orange wordcloud

You could change the randint range to make it brighter.

like image 65
Martin Evans Avatar answered Dec 21 '22 09:12

Martin Evans