from wordcloud import WordCloud #词云 import jieba #分词 from matplotlib import pyplot as plt #绘图 数据可视化 from PIL import Image #图片处理 import numpy as np #矩阵运算 import sqlite3 #数据库 # def show(): con = sqlite3.connect('movie.db') cur = con.cursor() sql = 'select instroduction from movie250' data = cur.execute(sql) text = "" for item in data: text = text + item[0] # print(text) cur.close() con.close() cut = jieba.cut(text) string = ' '.join(cut) print(len(string)) img = Image.open(r'./static/images/old.png') img_array = np.array(img) #将图片转换为数组 wc = WordCloud( background_color='white', mask=img_array, font_path="/Library/Fonts/Songti.ttc" #字体所在位置C:\Windows\Fonts ) wc.generate_from_text(string) #绘制图片 fig = plt.figure(1) plt.imshow(wc) plt.axis('off') #是否显示坐标轴 fig.patch.set_alpha(0) plt.show() #显示生成的词云图片 plt.savefig('static/images/new.png') # return img_array
时间: 2024-02-24 08:59:04 浏览: 76
在这段代码中,使用 `fig.patch.set_alpha(0)` 将整个图形对象的背景设置为透明,但是这里的 `fig` 指的是之前没有创建过的图形对象,因此这句代码并没有起到作用。
正确的方法是使用 `plt.gcf().patch.set_alpha(0)` 将当前的图形对象背景设置为透明,例如:
```python
import sqlite3
import jieba
import numpy as np
from wordcloud import WordCloud
from matplotlib import pyplot as plt
from PIL import Image
def show():
con = sqlite3.connect('movie.db')
cur = con.cursor()
sql = 'select instroduction from movie250'
data = cur.execute(sql)
text = ""
for item in data:
text = text + item[0]
cur.close()
con.close()
cut = jieba.cut(text)
string = ' '.join(cut)
print(len(string))
img = Image.open(r'./static/images/old.png')
img_array = np.array(img)
wc = WordCloud(
background_color='white',
mask=img_array,
font_path="/Library/Fonts/Songti.ttc"
)
wc.generate_from_text(string)
fig = plt.figure(1)
plt.imshow(wc)
plt.axis('off')
plt.gcf().patch.set_alpha(0) # 设置当前图形对象的背景为透明
plt.show()
plt.savefig('static/images/new.png')
# return img_array
```
阅读全文