Python Wordcloud:帮助获得(接近)设计师的要求

问题描述 投票:0回答:1

我正在从词频词典生成词云并得到以下结果:

通过使用以下词云参数:

wordcloud = WordCloud(
        width=667,
        height=375,
        font_path="resources/NotoSerif-SemiBold.ttf",
        prefer_horizontal=1,
        max_words=20,
        background_color="whitesmoke",
        min_font_size=11,
        max_font_size=64,
    ).generate_from_frequencies(freqdict)

我真正没有实现的是他们根据这些规格要求的颜色和尺寸方案: 你们中的任何人都可以至少达到他们想要的近似值吗?谢谢你

python data-science word-cloud
1个回答
0
投票

使用评论中提到的

color_func
,并借鉴如何使用
color_func
的更常见的在线示例(例如 这个示例这个 stackoverflow 问题),您可以非常接近以下颜色方案:已被要求。我猜你可以进一步磨练它以满足确切的要求,但这是一个很好的起点:

from wordcloud import (WordCloud, get_single_color_func)
import matplotlib.pyplot as plt


class GroupedColorFunc(object):
    """Create a color function object which assigns DIFFERENT SHADES of
       specified colors to certain words based on the words font size using a font-size range specified in a dictionary.

       Uses wordcloud.get_single_color_func

       Parameters
       ----------
       color_to_font_size : dict(str -> list(str))
         A dictionary that maps a color to a list containing the min and max font size.

       default_color : str
         Color that will be assigned to a word that's not a member
         of any value from color_to_words.
    """

    def __init__(self, color_to_font_size , default_color):
        self.color_func_to_words = [
            (get_single_color_func(color), list(font_size_range))
            for (color, font_size_range) in color_to_font_size.items()]
    
        print([(color_func, font_size_range) for (color_func, font_size_range) in self.color_func_to_words])
        
        self.default_color_func = get_single_color_func(default_color)

    def get_color_func(self, word, font_size):
        
        """Returns a single_color_func associated with the word"""
        try:
            color_func = next(
                color_func for (color_func, font_size_range) in self.color_func_to_words
                if (font_size >= font_size_range[0] and font_size <= font_size_range[1]))
        except StopIteration:
            color_func = self.default_color_func

        return color_func

    def __call__(self, word, font_size, **kwargs):
        return self.get_color_func(word, font_size)(word, font_size, **kwargs)


text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""

# Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(
        width=667,
        height=375,
        prefer_horizontal=1,
        #max_words=20,
        #font_path="resources/NotoSerif-SemiBold.ttf"
        background_color="whitesmoke",
        min_font_size=11,
        max_font_size=64).generate(text.lower())

color_to_font_size = {
    # color to font size ranges
    '#663871': [33,64],    
    '#333333': [15,32],
    '#6B6B6B': [0,14]
}

# Words that are not in any of the color_to_font_size values
# will be colored with this default color function
default_color = '#FFFFFF'

# Create a color function with multiple tones
grouped_color_func = GroupedColorFunc(color_to_font_size , default_color)

# Apply our color function
wc.recolor(color_func=grouped_color_func)

# Plot
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.