WordCloud制作词云(2)--以图片为轮廓附制作心形词云❤

官方教程链接地址
github项目地址

准备工作:

1. 安装matplotlib以及numpy
2. 文本内容(英文最好,官方不支持中文词分割,第三节涉及到中文支持问题,可跳转查看中文支持,可以直接复制文本,也可以读取文本文件)
3. 一张背景为白色的轮廓图(轮廓图尽量简洁较好,且背景为纯白色。)
from wordcloud import WordCloud
import os
import numpy as np
from PIL import Image 
import matplotlib.pyplot as plt
#1 直接复制文本信息
text=' Funch told the Associated Press (AP), “While the Romans were building their columns, their buildings, these termites were building their mounds.” He added that the dirt columns represent the largest natural construction of any species other than humans.'#复制你的文本信息在这里
#2 打开txt文本
#with open ('en_sentense.txt') as fp:
#    text=fp.read()
#轮廓图片获取
mask=np.array(Image.open('masked_001.jpg'))
word_cloud=WordCloud(background_color='white', max_words=2000,repeat=True, mask=mask,min_font_size=1)
word_cloud.generate(text)
word_cloud.to_file('mask_wordcloud.jpg')
#显示效果图
plt.axis("off")
plt.imshow(word_cloud, interpolation="bilinear")
plt.show()
WordCloud制作词云(2)--以图片为轮廓附制作心形词云❤_第1张图片
词云的轮廓图片(左)生成的词云(右)
如何实现绘制爱心呢?过程参考python画心型线传送门

接下来的事情就是将心形图内部染上颜色,即可将图片传递给wordcloud()函数。

函数matplotlib中的plt.fill_between(),matplotlib模块中fill函数详细使用传送门

结合两个方案后,就可以绘制心形图形了,代入wordcloud函数即可实现心形词云了。

import matplotlib.pyplot as plt
import numpy as np

#plt.title('heart', fontsize=24)#图名
x = np.linspace(-1, 1, 200)
# 把函数分为上下两个部分
y1 = np.sqrt(1-np.power(x, 2)) + np.power(np.square(x), 0.33)
y2 = -np.sqrt(1-np.power(x, 2)) + np.power(np.square(x), 0.33)
# 设置一下x轴、y轴的刻度和坐标间距,为了显示结果的美观,在此取消坐标轴
#my_x_ticks = np.arange(-2, 2.5, 0.5)
#my_y_ticks = np.arange(-2, 2.5, 0.5)
plt.plot(x, y1, color='r')#绘制心形上方部分
plt.plot(x, y2, color='r')#绘制下半部分
plt.fill_between(x,y1,y2,where=y1>=y2,facecolor='red',interpolate=True)#染色
#plt.xticks(my_x_ticks)#坐标刻度
#plt.yticks(my_y_ticks)
plt.axis('off')#取消显示坐标轴
plt.show()
WordCloud制作词云(2)--以图片为轮廓附制作心形词云❤_第2张图片
心形图效果

你可能感兴趣的:(WordCloud制作词云(2)--以图片为轮廓附制作心形词云❤)