我正在尝试从数据框中创建词云,其中有一个单词列和一个相应频率的列。我还下载了一张图片作为蒙版,例如:cloud image
我无法让词云适应蒙版 - 尽管按照示例所示进行操作。以下是我的代码:
from PIL import Image
import pandas as pd
import numpy as np
from wordcloud import WordCloud
import matplotlib.pyplot as plt
df = pd.DataFrame({'word':['time', 'car', 'Peter\'s', 'sky',
'something', 'computer', 'brain', 'plants',
'trees', 'Alien\'s', 'gun', 'eat'],
'freq':[24, 16, 16, 15,
14, 13, 12, 10,
9, 9, 5, 3]})
words = ' '.join(df['word'])
cloud_image = r"C:\Users\L\Documents\Python Scripts\cloud.png"
mask = np.array(Image.open(cloud_image))
wordcloud = WordCloud(max_words=2000,
width=1280,
height=720,
mask=mask)
wordcloud.generate_from_frequencies()
fig, ax = plt.subplots(figsize=(8, 6))
ax.imshow(wordcloud, interpolation='bilinear')
ax.axis("off")
ax.imshow(mask, interpolation='bilinear')
plt.show()
WordCloud()
有一个参数background_color
,你可以将其设置为'white'
以获得无背景的图像(我想是这样 - 已经有一段时间了)。 - fffrost