python中的字云,带有自定义颜色

时间:2017-03-27 09:54:58

标签: python

我看到这个函数在线生成一个词云但是我无法弄清楚如何更改def_random_func中的颜色说我现在想要橙色代码总是产生一个绿色的词云这里是代码:

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()

1 个答案:

答案 0 :(得分:4)

random_color_func()正在创建相同色调但具有不同亮度的颜色。你只需要决定你想要的色调。因此,对于橙色,您可以考虑使用值21,例如:

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)

色调值在0-360范围内,您可以使用在线颜色选择器查找合适的值(例如,尝试使用Google搜索colour picker)。代码只是转换范围0-255,这是另一个常见标准。因此,您只需转换h = 30而不是转换。

这会给你类似的东西:

orange wordcloud

您可以更改randint范围以使其更亮。