01 3D柱狀圖
from pyecharts.charts import Bar3D
from pyecharts import options as opts
from pyecharts.faker import Faker
from pyecharts.globals import ThemeType
import random
bar3d = Bar3D(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1200px',
height='720px'))
data = [(i,j,random.randint(0,12)) for i in range(20) for j in range(6)]
bar3d.add(
'3D柱形圖',
data,
xaxis3d_opts=opts.Axis3DOpts(Faker.clock,type_='category'),
yaxis3d_opts=opts.Axis3DOpts(Faker.week_en,type_='category'),
zaxis3d_opts=opts.Axis3DOpts(type_='value')
)
bar3d.set_global_opts(
visualmap_opts=opts.VisualMapOpts(max_=20),
title_opts=opts.TitleOpts(title='Bar3D-柱形圖')
)
bar3d.render('3D柱形圖.html')
print('生成成功')
01動(dòng)態(tài)散點(diǎn)圖
from pyecharts.faker import Faker
from pyecharts.charts import EffectScatter
import pyecharts.options as opts
from pyecharts.globals import SymbolType
effect_scatter = EffectScatter()
effect_scatter.add_xaxis(Faker.choose())
effect_scatter.add_yaxis(
'散點(diǎn)圖',
Faker.values(),
symbol=SymbolType.DIAMOND
)
effect_scatter.set_global_opts(title_opts=opts.TitleOpts(title='EffectScatter-散點(diǎn)圖'))
effect_scatter.render('動(dòng)態(tài)散點(diǎn)圖.html')
print('生成成功')
01數(shù)據(jù)可視化柱形圖
from pyecharts.charts import Bar
bar = Bar()
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y = [123,32,56,99,210,100]
bar.add_xaxis(x)
bar.add_yaxis('水果',y)
bar.render('柱狀圖.html')
print("執(zhí)行成功")
01餅圖
from pyecharts.faker import Faker
from pyecharts.charts import Pie
import pyecharts.options as opts
pie = Pie()
#pie.add('餅圖',[list(z) for z in zip(Faker.choose(),Faker.values())])
#pie.set_global_opts(title_opts=opts.TitleOpts(title='Pie-餅圖'))
#pie.set_series_opts(label_opts=opts.LabelOpts(formatter=':{c}'))
pie.add(
'餅圖',
[list(z) for z in zip(Faker.choose(),Faker.values())],
radius=['40%','75%'], # radius 表示內(nèi)環(huán)和外環(huán)半徑,列表類型
# rosetype設(shè)置玫瑰餅圖模式, area所有扇區(qū)圓心角相同,僅通過(guò)半徑展現(xiàn)數(shù)據(jù)大小
rosetype='area'
)
pie.set_global_opts(title_opts=opts.TitleOpts(title='Pie-餅圖'))
pie.set_series_opts(label_opts=opts.LabelOpts(formatter=':{c}'))
pie.render('玫瑰餅圖.html')
print("生成成功")
02折線圖
from pyecharts.faker import Faker
from pyecharts.charts import Line
import pyecharts.options as opts
line = Line()
line.add_xaxis(Faker.choose())
# is_smooth 是否讓折線變平滑
line.add_yaxis('商家A',Faker.values(),is_smooth=True)
line.add_yaxis('商家B',Faker.values())
line.set_global_opts(title_opts=opts.TitleOpts(title='折線圖'))
line.render('折線圖.html')
print('生成成功')
02漏斗圖
from pyecharts.faker import Faker
from pyecharts.charts import Funnel
import pyecharts.options as opts
from pyecharts.globals import SymbolType
funnel = Funnel()
funnel.add(
'用戶轉(zhuǎn)化率',
[list(z) for z in zip(Faker.choose(),Faker.values())],
label_opts=opts.LabelOpts(position='inside')
)
funnel.set_global_opts(title_opts=opts.TitleOpts(title="Funnel-漏斗圖"))
funnel.render('漏斗圖.html')
print('生成成功')
02鏈?zhǔn)秸{(diào)用
from pyecharts.charts import Bar
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y = [123,32,56,99,210,100]
Bar().add_xaxis(x).add_yaxis('水果',y).render('鏈?zhǔn)秸{(diào)用.html')
print("執(zhí)行成功")
03地理坐標(biāo)系
from pyecharts.faker import Faker
from pyecharts.charts import Geo
import pyecharts.options as opts
from pyecharts.globals import ThemeType
geo = Geo(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1600px',
height='800px'))
geo.add_schema(maptype='china')
geo.add('geo',
[list(z) for z in zip(Faker.provinces,Faker.values())],
type_='heatmap'
)
geo.set_global_opts(
visualmap_opts=opts.VisualMapOpts(),
title_opts=opts.TitleOpts(title='Geo-地圖')
)
geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
geo.render('地圖.html')
print("生成成功")
03填充漸變折線圖
from pyecharts.faker import Faker
from pyecharts.charts import Line
import pyecharts.options as opts
line = Line()
line.add_xaxis(Faker.choose())
# is_smooth 是否讓折線變平滑
line.add_yaxis('商家A',
Faker.values(),
is_smooth=True,
areastyle_opts=opts.AreaStyleOpts(
opacity=0.2,
color={
'type':'linear',
'x':0,
'y':0,
'x2':0,
'y2':1,
'colorStops':[{
'offset':0,'color':'red'},
{'offset':1,'color':'blue'
}]
}
)
)
line.add_yaxis('商家B',Faker.values())
line.set_global_opts(title_opts=opts.TitleOpts(title='折線圖'))
line.render('漸變折線圖.html')
print('生成成功')
添加標(biāo)題
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = Bar()
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y = [123,32,56,99,210,100]
bar.add_xaxis(x)
bar.add_yaxis('水果',y)
bar.set_global_opts(title_opts=opts.TitleOpts(title='水果數(shù)量',
subtitle='副標(biāo)題'))
bar.render('添加標(biāo)題.html')
print("執(zhí)行成功")
更改尺寸
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
bar = Bar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1920px',
height='1080px'))
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y = [123,32,56,99,210,100]
bar.add_xaxis(x)
bar.add_yaxis('水果',y)
bar.set_global_opts(title_opts=opts.TitleOpts(title='水果數(shù)量',subtitle='副標(biāo)題'))
bar.render('圖表尺寸.html')
print("執(zhí)行成功")
水球圖
from pyecharts.charts import Liquid
import pyecharts.options as opts
liquid = Liquid()
# is_outline_show 是否顯示外邊框
# is_animation 是否顯示動(dòng)畫效果
# shape 邊框形狀,和symbol可用的形狀類似,還可以自定義
liquid.add('水球圖',[0.7,0.6,0.5])
liquid.set_global_opts(title_opts=opts.TitleOpts(title='Liquid-水球圖'))
liquid.render('水球圖.html')
print('成功創(chuàng)建')
旋轉(zhuǎn)X軸標(biāo)簽
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
bar = Bar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1000px',
height='720px'))
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y = [123,32,56,99,210,100]
bar.add_xaxis(x)
bar.add_yaxis('水果',y)
bar.set_global_opts(title_opts=opts.TitleOpts(
title='水果數(shù)量',
subtitle='副標(biāo)題'),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=30)))# -90°到90°
bar.render('旋轉(zhuǎn)x軸.html')
print("執(zhí)行成功")
雷達(dá)圖
from pyecharts.charts import Radar
import pyecharts.options as opts
from pyecharts.globals import ThemeType
radar = Radar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1700px',
height='800px'))
v1 = [
[4300,31560,28000,25626,19000,15000],
[3300,30000,26000,25000,17000,16000]
]
v2 = [[5000,14000,25000,19000,35000,18000]]
radar.add_schema(
schema=[
opts.RadarIndicatorItem(name='銷售',max_=6500),
opts.RadarIndicatorItem(name='管理',max_=16000),
opts.RadarIndicatorItem(name='信息技術(shù)',max_=9900),
opts.RadarIndicatorItem(name='客服',max_=6900),
opts.RadarIndicatorItem(name='研發(fā)',max_=18000),
opts.RadarIndicatorItem(name='市場(chǎng)',max_=12600)
]
)
radar.add('預(yù)算分配',v1)
radar.add('實(shí)際開(kāi)銷',v2)
radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
radar.set_global_opts(title_opts=opts.TitleOpts(title='Radar-雷達(dá)圖'))
radar.render('雷達(dá)圖.html')
print('生成成功')
傳入兩組數(shù)據(jù)
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 設(shè)置圖表大小
bar = Bar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1000px',
height='720px'))
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y1 = [123,32,56,99,210,100]
y2 = [100,132,46,69,90,120]
bar.add_xaxis(x)
bar.add_yaxis('水果1',y1)
bar.add_yaxis('水果2',y2)
# 將數(shù)據(jù)堆疊在一起,可以將兩兩數(shù)據(jù)進(jìn)行堆疊,用stack方法
#bar.add_yaxis('水果1',y1,stack='stack1')
#bar.add_yaxis('水果2',y2,stack='stack1')
bar.set_global_opts(title_opts=opts.TitleOpts(
title='水果數(shù)量',
subtitle='副標(biāo)題'))
bar.render('兩組數(shù)據(jù).html')
print("執(zhí)行成功")
詞云圖
from pyecharts.charts import WordCloud
import pyecharts.options as opts
words = [
('Sam S Club',10000),
('Macys',6000),
('Amy Schumer',4300),
('Beautifully',5000),
('Congratulations',6500),
('Jurassic',4500),
('Love',5500),
('Honorable',3900),
('King',4800),
]
wordcloud = WordCloud()
wordcloud.add('詞云圖',words,word_size_range=[20,100])
wordcloud.set_global_opts(title_opts=opts.TitleOpts(title='WordCloud-詞云圖'))
wordcloud.render('詞云圖.html')
print('生成成功')
07圖表標(biāo)記點(diǎn)和標(biāo)記線
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 設(shè)置圖表大小
bar = Bar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1000px',
height='720px'))
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y1 = [123,32,56,99,210,100]
y2 = [100,132,46,69,90,120]
bar.add_xaxis(x)
bar.add_yaxis('水果1',y1)
bar.add_yaxis('水果2',y2)
# 設(shè)置標(biāo)題
bar.set_global_opts(title_opts=opts.TitleOpts(
title='水果數(shù)量',
subtitle='副標(biāo)題'))
# 設(shè)置標(biāo)記點(diǎn)和標(biāo)記線
bar.set_series_opts(
label_opts=opts.LabelOpts(is_show=False),
markpoint_opts=opts.MarkPointOpts(
data=[
opts.MarkPointItem(type_='max',name='最大值'),
opts.MarkPointItem(type_='min',name='最小值')
]
),
markline_opts=opts.MarkLineOpts(
data=[opts.MarkPointItem(type_='average',name='平均值')]
)
)
# x軸與y軸互換
#bar.reversal_axis()
bar.render('標(biāo)記點(diǎn)和標(biāo)記線.html')
print("執(zhí)行成功")
08窗口滑塊
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# 設(shè)置圖表大小
bar = Bar(init_opts=opts.InitOpts(
theme=ThemeType.PURPLE_PASSION,
width='1000px',
height='720px'))
x = ['葡萄','橘子','香蕉','榴蓮','蘋果','梨']
y1 = [123,32,56,99,210,100]
y2 = [100,132,46,69,90,120]
bar.add_xaxis(x)
bar.add_yaxis('水果1',y1)
bar.add_yaxis('水果2',y2)
# 設(shè)置標(biāo)題
bar.set_global_opts(
title_opts=opts.TitleOpts(
title='水果數(shù)量',
subtitle='副標(biāo)題'),
# 設(shè)置窗口滑塊
datazoom_opts=[opts.DataZoomOpts()]
)
# 設(shè)置標(biāo)記點(diǎn)和標(biāo)記線
bar.set_series_opts(
label_opts=opts.LabelOpts(is_show=False),
markpoint_opts=opts.MarkPointOpts(
data=[
opts.MarkPointItem(type_='max',name='最大值'),
opts.MarkPointItem(type_='min',name='最小值')
]
),
markline_opts=opts.MarkLineOpts(
data=[opts.MarkPointItem(type_='average',name='平均值')]
)
)
bar.render('窗口滑塊.html')
print("執(zhí)行成功")
echarts_option_query
import re
import asyncio
from aiohttp import TCPConnector, ClientSession
import pyecharts.options as opts
from pyecharts.charts import TreeMap
async def get_json_data(url: str) -> dict:
async with ClientSession(connector=TCPConnector(ssl=False)) as session:
async with session.get(url=url) as response:
return await response.json()
# 獲取官方的數(shù)據(jù)
data = asyncio.run(
get_json_data(
url="https://echarts.apache.org/examples/data/asset/data/ec-option-doc-statistics-201604.json"
)
)
tree_map_data: dict = {"children": []}
def convert(source, target, base_path: str):
for key in source:
if base_path != "":
path = base_path + "." + key
else:
path = key
if re.match(r"/^\$/", key):
pass
else:
child = {"name": path, "children": []}
target["children"].append(child)
if isinstance(source[key], dict):
convert(source[key], child, path)
else:
target["value"] = source["$count"]
convert(source=data, target=tree_map_data, base_path="")
(
TreeMap(init_opts=opts.InitOpts(width="1900px", height="720px"))
.add(
series_name="option",
data=tree_map_data["children"],
visual_min=300,
leaf_depth=1,
# 標(biāo)簽居中為 position = "inside"
label_opts=opts.LabelOpts(position="inside"),
)
.set_global_opts(
legend_opts=opts.LegendOpts(is_show=False),
title_opts=opts.TitleOpts(
title="Echarts 配置項(xiàng)查詢分布", subtitle="2020/9", pos_left="leafDepth"
),
)
.render("echarts_option_query.html")
)
graph_weibo
import json
from pyecharts import options as opts
from pyecharts.charts import Graph
with open("weibo.json", "r", encoding="utf-8") as f:
j = json.load(f)
nodes, links, categories, cont, mid, userl = j
print(nodes, links, categories, cont, mid, userl)
c = (
Graph(init_opts=opts.InitOpts(width='1700px',height='820px'))
.add(
"",
nodes,
links,
categories,
repulsion=50,
linestyle_opts=opts.LineStyleOpts(curve=0.2),
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
legend_opts=opts.LegendOpts(is_show=False),
title_opts=opts.TitleOpts(title="Graph-微博轉(zhuǎn)發(fā)關(guān)系圖"),
)
.render("graph_weibo1.html")
)
print("=================創(chuàng)建成功===================")
rain
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 確定再現(xiàn)性的隨機(jī)狀態(tài)
np.random.seed(19680801)
# 創(chuàng)建新圖形和填充它的軸
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])
# 創(chuàng)建雨水?dāng)?shù)據(jù)
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
# 在隨機(jī)位置初始化雨滴
# 隨機(jī)增長(zhǎng)率
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
# 構(gòu)建我們將在動(dòng)畫期間更新的散射
# 隨雨滴發(fā)展
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')
def update(frame_number):
# 得到一個(gè)索引,我們可以用來(lái)重新生成雨滴。
current_index = frame_number % n_drops
# 隨著時(shí)間的推移,使所有顏色更加透明。
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)
# 把所有的圓圈變大
rain_drops['size'] += rain_drops['growth']
# 為雨滴選擇一個(gè)新的位置,重置其大小
# 顏色
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
rain_drops['size'][current_index] = 5
rain_drops['color'][current_index] = (0, 0, 0, 1)
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
# 使用新的顏色、大小和位置更新散布集合
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
# 構(gòu)造動(dòng)畫,使用更新函數(shù)作為動(dòng)畫
animation = FuncAnimation(fig, update, interval=10)
plt.show()
temperature_change_line_chart
import pyecharts.options as opts
from pyecharts.charts import Line
week_name_list = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
high_temperature = [11, 11, 15, 13, 12, 13, 10]
low_temperature = [1, -2, 2, 5, 3, 2, 0]
(
Line(init_opts=opts.InitOpts(width='1600px',height='620px'))
.add_xaxis(xaxis_data=week_name_list)
.add_yaxis(
series_name="最高氣溫",
y_axis=high_temperature,
markpoint_opts=opts.MarkPointOpts(
data=[
opts.MarkPointItem(type_="max", name="最大值"),
opts.MarkPointItem(type_="min", name="最小值"),
]
),
markline_opts=opts.MarkLineOpts(
data=[opts.MarkLineItem(type_="average", name="平均值")]
),
)
.add_yaxis(
series_name="最低氣溫",
y_axis=low_temperature,
markpoint_opts=opts.MarkPointOpts(
data=[opts.MarkPointItem(value=-2, name="周最低", x=1, y=-1.5)]
),
markline_opts=opts.MarkLineOpts(
data=[
opts.MarkLineItem(type_="average", name="平均值"),
opts.MarkLineItem(symbol="none", x="90%", y="max"),
opts.MarkLineItem(symbol="circle", type_="max", name="最高點(diǎn)"),
]
),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="未來(lái)一周氣溫變化", subtitle="純屬虛構(gòu)"),
tooltip_opts=opts.TooltipOpts(trigger="axis"),
toolbox_opts=opts.ToolboxOpts(is_show=True),
xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
)
.render("temperature_change_line_chart.html")
)
print("="*50)
動(dòng)態(tài)曲線圖
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def Gen_RandLine(length, dims=2):
# 使用隨機(jī)游走算法創(chuàng)建一條直線。長(zhǎng)度是直線的點(diǎn)數(shù)。dims是線的尺寸。
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims) # 初始化起點(diǎn)
for index in range(1, length):
step = ((np.random.rand(dims) - 0.5) * 0.12) # 步長(zhǎng)
# 下一步的位置
lineData[:, index] = lineData[:, index - 1] + step
return lineData # 返回一個(gè)shape為(3,25)的數(shù)組,3維坐標(biāo)25幀
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
fig = plt.figure()
ax = p3.Axes3D(fig)
# 長(zhǎng)為50的數(shù)組,每個(gè)元素為shape為3,25的ndarray,最后實(shí)際效果就是50條路徑
data = [Gen_RandLine(25, 3) for index in range(50)]
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data] # 每條路徑的起始點(diǎn)
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')
ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')
ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),interval=50, blit=False)
plt.show()
print("="*50)
動(dòng)態(tài)直線
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
plt.style.use('dark_background')
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)
# 初始化函數(shù)
def init():
# 創(chuàng)建空打印/幀
line.set_data([], [])
return line,
# 存儲(chǔ)x軸和y軸點(diǎn)的列表
xdata, ydata = [], []
def ghostImage(x,y):
xdata.append(x)
ydata.append(y)
if len(xdata)>60:
del xdata[0]
del ydata[0]
return xdata,ydata
def animate(i):
t = i/100.0
x = 40*np.sin(2*2*np.pi*(t+0.3))
y = 40*np.cos(3*2*np.pi*t)
# 將新點(diǎn)附加到x、y軸點(diǎn)列表
line.set_data(ghostImage(x,y))
return line,
# 繪圖標(biāo)題設(shè)置
plt.title('Creating a Lissajous figure with matplotlib')
# 隱藏軸細(xì)節(jié)
plt.axis('off')
anim = animation.FuncAnimation(fig, animate,init_func=init,frames=400, interval=20, blit=True)
# 將動(dòng)畫另存為gif文件
anim.save('figure.gif',writer='imagemagick')
旋轉(zhuǎn)line3D
import math
from pyecharts import options as opts
from pyecharts.charts import Line3D
from pyecharts.faker import Faker
data = []
for t in range(0, 25000):
_t = t / 1000
x = (1 + 0.25 * math.cos(75 * _t)) * math.cos(_t)
y = (1 + 0.25 * math.cos(75 * _t)) * math.sin(_t)
z = _t + 2.0 * math.sin(75 * _t)
data.append([x, y, z])
c = (
Line3D(init_opts=opts.InitOpts(width='1600px',height='620px'))
.add(
"",
data,
xaxis3d_opts=opts.Axis3DOpts(Faker.clock, type_="value"),
yaxis3d_opts=opts.Axis3DOpts(Faker.week_en, type_="value"),
grid3d_opts=opts.Grid3DOpts(
width=100, depth=100, rotate_speed=150, is_rotate=True
),
)
.set_global_opts(
visualmap_opts=opts.VisualMapOpts(
max_=30, min_=0, range_color=Faker.visual_color
),
title_opts=opts.TitleOpts(title="Line3D-旋轉(zhuǎn)的彈簧"),
)
.render("line3d_autorotate.html")
)
print("=========================生成成功============================")
詞云圖
import jieba
from matplotlib import pyplot as plt
from wordcloud import WordCloud
from PIL import Image
import numpy as np
#r''單引號(hào)里面不需要轉(zhuǎn)義
path = r'D:\pycharm\test1\進(jìn)階篇\素材'
font = r'C:\Windows\Fonts\SIMKAI.TTF'#電腦自帶的字體
def tcg(texts):
cut = jieba.cut(texts) #分詞
string = ' '.join(cut)
return string
text = (open(path+r'./cloud.txt','r',encoding='utf-8')).read()
string=tcg(text)
img = Image.open(path+r'./1.png') #打開(kāi)圖片
img_array = np.array(img) #將圖片裝換為數(shù)組
stopword=[''] #設(shè)置停止詞,也就是你不想顯示的詞
wc = WordCloud(
background_color='white',
width=1000,
height=800,
mask=img_array, #設(shè)置背景圖片
font_path=font,
stopwords=stopword
)
wc.generate_from_text(string)#繪制圖片
plt.imshow(wc)
plt.axis('off')
plt.show() #顯示圖片
wc.to_file(path+'./beautifulcloud.png') #保存圖片