瞎折腾系列
咳咳, 无耻狗贼又抄来了一篇博文
参考链接:
- https://towardsdatascience.com/how-to-create-beautiful-word-clouds-in-python-cfcf85141214
- https://matplotlib.org/stable/tutorials/colors/colormaps.html
- https://blog.csdn.net/qq_34604224/article/details/121391890
- https://www.datacamp.com/community/tutorials/wordcloud-python
先上代码, 通过指定 colormap='XXX'
这个属性可以使用不同的配色集
# 转换
def transform_format(val):
if val == 0:
return 255
else:
return val
mask = np.array(Image.open('plugins/groupword/bg.png'))
image_colors = ImageColorGenerator(mask)
# 处理mask无效问题
mask = mask[:,:,0]
transformed_mask = np.ndarray((mask.shape[0],mask.shape[1]), np.int32)
for i in range(len(mask)):
transformed_mask[i] = list(map(transform_format, mask[i]))
word_cloud = WordCloud(font_path="plugins/groupword/wqy-microhei.ttc",
background_color='rgba(255, 255, 255, 0)', # 这个决定背景颜色
mode='RGBA',
colormap='Spectral', # 配色集
#mask=transformed_mask,
#color_func = image_colors, # 决定文字颜色, 文字覆盖在图片的什么位置就取图片对应位置的颜色.
#contour_width = 3, # 边框宽度
#width=800, # 指定长寛, 单位像素, 指定mask后属性不生效
#height=800,
#max_font_size=150, # 设置字体最大值
#random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
#max_words=2000, # 设置最大显示的字数
collocations=True, # 打开后去除重复词
).generate_from_frequencies(words)
自定义颜色
自定义颜色的需求, 用下面这个方式应该可以实现: 指定一张只包含了想要自定义颜色的图片, 用 ImageColorGenerator
提取出颜色, 设置到wordcloud, 这里不要使用 colormap
, 用 color_func
这个参数
from wordcloud import WordCloud,ImageColorGenerator
mask = np.array(Image.open('plugins/groupword/bg.png'))
image_colors = ImageColorGenerator(mask) # 从图片提取颜色
colormap 配色集 (参考链接2)
- Sequential
['viridis', 'plasma', 'inferno', 'magma', 'cividis']
['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']
- Sequential2
['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone',
'pink', 'spring', 'summer', 'autumn', 'winter', 'cool',
'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']
- Diverging
['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu',
'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']
- Cyclic
['twilight', 'twilight_shifted', 'hsv']
- Qualitative
['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',
'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',
'tab20c']
- Miscellaneous
['flag', 'prism', 'ocean', 'gist_earth', 'terrain',
'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap',
'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet',
'turbo', 'nipy_spectral', 'gist_ncar']