Python wordcloud color by term frequency

Viewed 4116

I new in python and I a using wordcloud pkg.

I generated a word cloud by frequencies that I have in a dict frequencies with keys=words and values=frequencies of the words.

The wordcloud can receive a function in the color_funct parameter. Such function can be used to make your own colormap for the words on the cloud. As example I used my_tf_color_func.

wordcloud = WordCloud(background_color="white", max_words=1000, mask=motog3_coloring,
max_font_size=1000, random_state=1,  relative_scaling=.6, regexp="\w[\%\-\(\)\w']+",
collocations=False, color_func=my_tf_color_func)

In my_tf_color_func I want to color each word according to its frequency in the attribute frequencies. I now that I can do something like bellow in my_tf_color_func, given the report on this issue

def my_tf_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
         return "hsl(%d, 80%%, 50%%)" % (360 * frequencies[word])

But the dict frequencies has to be passed, how can I do that? Where and how I must pass the dict frequencies to be able to use it in my_tf_color_func.

I tried in some ways but I could not.

Many Thanks

1 Answers

You could close over it explicitly using something like this:

def my_tf_color_func(dictionary):
  def my_tf_color_func_inner(word, font_size, position, orientation, random_state=None, **kwargs):
    return "hsl(%d, 80%%, 50%%)" % (360 * dictionary[word])
  return my_tf_color_func_inner

wordcloud = WordCloud(...,color_func=my_tf_color_func(frequencies))

An alternative for explicitly stateful function-like objects would be something like:

class MyColorFunctor():
  def __init__(self,frequencies):
    self.frequencies = frequencies

  def __call__(self,word,font_size,position,orientation,random_state=None,**kwargs):
    return "hsl(%d, 80%%, 50%%)" % (360 * self.frequencies[word])

wordcloud = WordCloud(...,color_func=MyColorFunctor(frequencies))
Related