def test_sankey_base(fake_writer): nodes = [{ "name": "category1" }, { "name": "category2" }, { "name": "category3" }] links = [ { "source": "category1", "target": "category2", "value": 10 }, { "source": "category2", "target": "category3", "value": 15 }, ] c = Sankey().add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) c.render() _, content = fake_writer.call_args[0] assert_equal(c.theme, "white") assert_equal(c.renderer, "canvas")
def test_sankey_base(): nodes = [{ "name": "category1" }, { "name": "category2" }, { "name": "category3" }] links = [ { "source": "category1", "target": "category2", "value": 10 }, { "source": "category2", "target": "category3", "value": 15 }, ] c = Sankey().add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) assert c.theme == "white" assert c.renderer == "canvas" c.render("render.html")
def show_sankey_figure(self, figure_name, title): sankey = Sankey(init_opts=opts.InitOpts(width='600px', height='600px')) sankey.add( "", self.format_nodes, self.links, levels=[ opts.SankeyLevelsOpts( depth=0, linestyle_opts=opts.LineStyleOpts(color="source", curve=0.5, opacity=0.6), itemstyle_opts=opts.ItemStyleOpts(border_width=0), ), opts.SankeyLevelsOpts( depth=1, itemstyle_opts=opts.ItemStyleOpts(border_width=0), linestyle_opts=opts.LineStyleOpts(color="target", curve=0.5, opacity=0.6), ), opts.SankeyLevelsOpts( depth=2, itemstyle_opts=opts.ItemStyleOpts(border_width=0)), ], pos_right="13%", node_gap=1, label_opts=opts.LabelOpts(position="right"), ) sankey.set_global_opts( title_opts=opts.TitleOpts(title=title, pos_left='center')) sankey.render("figure_html\{}.html".format(figure_name))
def sankey_base() -> Sankey: nodes = [ {"name": "category1"}, {"name": "category2"}, {"name": "category3"}, {"name": "category4"}, {"name": "category5"}, {"name": "category6"}, ] links = [ {"source": "category1", "target": "category2", "value": 10}, {"source": "category2", "target": "category3", "value": 15}, {"source": "category3", "target": "category4", "value": 20}, {"source": "category5", "target": "category6", "value": 25}, ] c = ( Sankey() .add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts(title_opts=opts.TitleOpts(title="Sankey-基本示例")) ) return c
def make_sanky(): links = [] nodes1 = [{'name': i} for i in A] nodes2 = [{'name': j} for j in B] nodes1.sort(key=lambda x: x['name']) nodes2.sort(key=lambda x: x['name']) nodes1.extend(nodes2) # 制作节点图 for j in dict_card.keys(): for k in dict_card[j]: links.append({ 'source': k, 'target': j, 'value': np.random.randint(15) }) links.sort(key=lambda x: x['source']) links = list(map(value2str, links)) # 制作关系图 # 绘制桑吉图 C = (Sankey(init_opts=opt.InitOpts(width='1100px', height='600px')).add( '', nodes1, links, linestyle_opt=opt.LineStyleOpts(opacity=0.5, curve=0.5, color='target', type_='dotted'), label_opts=opt.LabelOpts(position='left', ), ).set_global_opts(title_opts=opt.TitleOpts(title='随机分配'))) C.render('random assignments.html')
def sankey_base(sankey_data,district,school_name): nodes=[] links = [] # school_name = None for col in sankey_data.columns: for i in sankey_data[col].unique(): nodes.append({'name':str(i),'value':int(sankey_data[sankey_data[col] == i].count().iloc[0])}) school2score_data = pd.DataFrame(sankey_data.groupby(['juniormiddleschool','score_cut'])['highschool'].count()).reset_index() school2score_data = school2score_data.sort_values(by='score_cut',ascending=False) score_data2highschool = pd.DataFrame(sankey_data.groupby(['score_cut','highschool'])['juniormiddleschool'].count()).reset_index() score_data2highschool = score_data2highschool.sort_values(by='score_cut',ascending=False) for idx in school2score_data.index: links.append({"source": school2score_data.loc[idx,'juniormiddleschool'], "target": str(school2score_data.loc[idx,'score_cut']), "value": int(school2score_data.loc[idx,'highschool'])}) for idx in score_data2highschool.index: links.append({"source": str(score_data2highschool.loc[idx,'score_cut']), "target": score_data2highschool.loc[idx,'highschool'], "value": int(score_data2highschool.loc[idx,'juniormiddleschool'])}) c = ( Sankey(init_opts=opts.InitOpts(height='900px',width='1750px')) .add( "", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts(title_opts=opts.TitleOpts(title=f"{district}-{school_name}定向志愿同分数段去向")) ) return c
def sankey_base() -> Sankey: cities_nodes = [ {'name':'died'}, {'name':'confirmed'}, {'name':'suspected'}, {"name":'cured'} ] for c in [city['provinceName'] for city in ncov_data]: cities_nodes.append({"name":c}) confirmed_nodes=[city['confirmedCount'] for city in ncov_data] suspected_nodes=[city['suspectedCount'] for city in ncov_data] cured_nodes=[city['curedCount'] for city in ncov_data] links = [ ] for i,cn in enumerate(confirmed_nodes): links.append({'source':ncov_data[i]['provinceName'],"target":'confirmed',"value":cn}) #疑似 for i, sn in enumerate(suspected_nodes): links.append({'source': ncov_data[i]['provinceName'], "target": 'suspected', "value": sn}) for i, cn in enumerate(cured_nodes): links.append({'source': ncov_data[i]['provinceName'] ,"target": 'cured', "value": cn}) c = ( Sankey() .add( "nCoV-sankey", cities_nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts(title_opts=opts.TitleOpts(title="Sankey-疫情图")) ) c.render() return c
def timeline_sankey() -> Timeline: tl = Timeline() names = ("商家A", "商家B", "商家C") nodes = [{"name": name} for name in names] for i in range(2015, 2020): links = [ {"source": names[0], "target": names[1], "value": Faker.values()[0]}, {"source": names[1], "target": names[2], "value": Faker.values()[0]}, ] sankey = ( Sankey() .add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts( opacity=0.2, curve=0.5, color="source" ), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts( title_opts=opts.TitleOpts(title="{}年商店(A, B, C)营业额差".format(i)) ) ) tl.add(sankey, "{}年".format(i)) return tl
def SSC_plot(nodes, linkes, title_ssc, out): c = (Sankey().add( title_ssc, nodes, linkes, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ).set_global_opts(title_opts=opts.TitleOpts(title="约化图谱")).render(out)) print("约化图谱保存于 " + c)
def sankey_offical() -> Sankey: with open(os.path.join("fixtures", "energy.json"), "r", encoding="utf-8") as f: j = json.load(f) c = (Sankey().add( "sankey", nodes=j["nodes"], links=j["links"], linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ).set_global_opts(title_opts=opts.TitleOpts(title="Sankey-官方示例"))) return c
def get_sankey_view(all_nodes, all_links) -> Sankey: colors = [ "#67001f", "#b2182b", "#d6604d", "#f4a582", "#fddbc7", "#d1e5f0", "#92c5de", "#4393c3", "#2166ac", "#053061", ] # all_node_ids, all_link_ids = get_all_wechat_bill(False) c = ( Sankey().set_colors(colors).add( "sankey", all_nodes, all_links, pos_bottom="10%", pos_left="20%", node_width=10, is_draggable=True, focus_node_adjacency="allEdges", linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="left"), ) # .add( # "All", # all_node_ids, # all_link_ids, # pos_bottom="10%", # pos_left="20%", # node_width=10, # is_draggable=True, # focus_node_adjacency="allEdges", # linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), # label_opts=opts.LabelOpts(position="left"), # ) .set_global_opts( title_opts=opts.TitleOpts(title="Sankey"), tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"), )) return c.dump_options_with_quotes()
def page_Sankey(nodes_links, title_name): # 使用Sankey()函数创建对象赋值给sankey # 使用InitOpts(),传入参数theme="dark",bg_color="#253441",赋值给init_opts sankey = Sankey(init_opts=opts.InitOpts(theme="dark", bg_color="#253441")) # 为创建的实例增加名字(sankey)、传入实验组节点和信息流列表 sankey.add( "sankey", nodes=nodes_links[0], links=nodes_links[1], # 使用LineStyleOpts(),传入参数opacity=0.3, curve=0.5, color="source",赋值给linestyle_opt linestyle_opt=opts.LineStyleOpts(opacity=0.3, curve=0.5, color="source"), # 使用LabelOpts(),传入参数position="right",color="white",font_size=10,赋值给label_opts label_opts=opts.LabelOpts(position="right", color="white", font_size=10), # 使用SankeyLevelsOpts(),传入参数depth为0-5、itemstyle_opts,赋值给列表levels levels=[ opts.SankeyLevelsOpts( depth=0, # 使用ItemStyleOpts(),传入参数color="#FF8947",border_color="#FF8947" itemstyle_opts=opts.ItemStyleOpts(color="#FF8947", border_color="#FF8947")), opts.SankeyLevelsOpts( depth=1, # 使用ItemStyleOpts(),传入参数color="#96D15C",border_color="#96D15C" itemstyle_opts=opts.ItemStyleOpts(color="#96D15C", border_color="#96D15C")), opts.SankeyLevelsOpts( depth=2, # 使用ItemStyleOpts(),传入参数color="#479BED",border_color="#479BED" itemstyle_opts=opts.ItemStyleOpts(color="#479BED", border_color="#479BED")), opts.SankeyLevelsOpts( depth=3, # 使用ItemStyleOpts(),传入参数color="#55C4CA",border_color="#55C4CA" itemstyle_opts=opts.ItemStyleOpts(color="#55C4CA", border_color="#55C4CA")), opts.SankeyLevelsOpts( depth=4, # 使用ItemStyleOpts(),传入参数color="#E7BF4F",border_color="#E7BF4F" itemstyle_opts=opts.ItemStyleOpts(color="#E7BF4F", border_color="#E7BF4F")) ]) # 使用TitleOpts(),传入参数title,赋值给title_opts # 使用LegendOpts(),传入参数is_show=False,赋值给legend_opts # 调用set_global_opts() sankey.set_global_opts(title_opts=opts.TitleOpts(title=title_name), legend_opts=opts.LegendOpts(is_show=False)) # 使用return返回sankey return sankey
def sankey_base(links) -> Sankey: nodes = [ { "name": "出发:餐饮购物生活区附近" }, { "name": "出发:住宅区附近" }, { "name": "出发:公司商务区附近" }, { "name": "出发:其他区域" }, { "name": "到达:餐饮购物生活区附近" }, { "name": "到达:住宅区附近" }, { "name": "到达:公司商务区附近" }, { "name": "到达:其他区域" }, ] links = links c = (Sankey(init_opts=opts.InitOpts(theme=ThemeType.DARK)).add( "", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ).set_global_opts(title_opts=opts.TitleOpts( title="出发地-到达地位置附近poi + 具体小时")).set_series_opts( label_opts=opts.LabelOpts(color='white', position='right'))) return c
def plot_referral_path(date): import json filepath = 'out/referral_path' + date + ".json" with open(filepath, 'r') as fin: referraljson = json.load(fin) import pyecharts.options as opts from pyecharts.charts import Sankey plottitle = "top_referral_pages" + date plotpath = "fig/top_referral_pages" + date + ".html" Sankey() \ .add( "sankey", nodes=referraljson["nodes"], links=referraljson["links"], linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) \ .set_global_opts(title_opts=opts.TitleOpts(title=plottitle)) \ .render(plotpath)
def sankey_with_level_setting() -> Sankey: with open(os.path.join("fixtures", "product.json"), "r", encoding="utf-8") as f: j = json.load(f) c = (Sankey().add( "sankey", nodes=j["nodes"], links=j["links"], pos_top="10%", focus_node_adjacency=True, levels=[ opts.SankeyLevelsOpts( depth=0, itemstyle_opts=opts.ItemStyleOpts(color="#fbb4ae"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=1, itemstyle_opts=opts.ItemStyleOpts(color="#b3cde3"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=2, itemstyle_opts=opts.ItemStyleOpts(color="#ccebc5"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=3, itemstyle_opts=opts.ItemStyleOpts(color="#decbe4"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), ], linestyle_opt=opts.LineStyleOpts(curve=0.5), ).set_global_opts( title_opts=opts.TitleOpts(title="Sankey-Level Settings"), tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"), )) return c
data = pandas.read_excel('D:/Coding/Python/pyecharts/ly.xlsx', sheet_name='1') nodes = [] for i in set(pandas.concat([data.来源地, data.输入地])): d1 = {} d1['name'] = i nodes.append(d1) links = [] for x, y, z in zip(data.来源地, data.输入地, data.数量): d2 = {} d2['source'] = x d2['target'] = y d2['value'] = z links.append(d2) pic = ( #创角桑基图对象,设置画布大小 Sankey(init_opts=opts.InitOpts(width="1600px", height="800px")).add( '确诊病例', #图例名称 nodes, #节点数据 links, #边和流量数据 #设置透明度、弯曲度、颜色 linestyle_opt=opts.LineStyleOpts(opacity=0.3, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), #标签显示位置 node_gap=10 #节点之前的距离 ).set_global_opts(title_opts=opts.TitleOpts(title='TOP10境外输入统计'))) pic.render('TOP10境外输入统计.html')
def test_sankey_new_opts(fake_writer): nodes = [ { "name": "a" }, { "name": "b" }, { "name": "a1" }, { "name": "b1" }, { "name": "c" }, { "name": "e" }, ] links = [ { "source": "a", "target": "a1", "value": 5 }, { "source": "e", "target": "b", "value": 3 }, { "source": "a", "target": "b1", "value": 3 }, { "source": "b1", "target": "a1", "value": 1 }, { "source": "b1", "target": "c", "value": 2 }, { "source": "b", "target": "c", "value": 1 }, ] c = Sankey().add( "sankey", nodes, links, pos_bottom="10%", focus_node_adjacency="allEdges", orient="vertical", levels=[ opts.SankeyLevelsOpts( depth=0, itemstyle_opts=opts.ItemStyleOpts(color="#eee"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ) ], linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) c.render() _, content = fake_writer.call_args[0] assert_in("bottom", content) assert_in("orient", content) assert_in("levels", content) assert_in("focusNodeAdjacency", content)
from pyecharts import options as opts from pyecharts.charts import Sankey, Timeline from pyecharts.faker import Faker tl = Timeline() names = ("商家A", "商家B", "商家C") nodes = [{"name": name} for name in names] for i in range(2015, 2020): links = [ {"source": names[0], "target": names[1], "value": Faker.values()[0]}, {"source": names[1], "target": names[2], "value": Faker.values()[0]}, ] sankey = ( Sankey() .add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts( title_opts=opts.TitleOpts(title="{}年商店(A, B, C)营业额差".format(i)) ) ) tl.add(sankey, "{}年".format(i)) tl.render("Timeline_sankey.html")
c = (Sankey().add( "sankey", nodes=j["nodes"], links=j["links"], pos_top="10%", focus_node_adjacency=True, levels=[ opts.SankeyLevelsOpts( depth=0, itemstyle_opts=opts.ItemStyleOpts(color="#fbb4ae"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=1, itemstyle_opts=opts.ItemStyleOpts(color="#b3cde3"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=2, itemstyle_opts=opts.ItemStyleOpts(color="#ccebc5"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=3, itemstyle_opts=opts.ItemStyleOpts(color="#decbe4"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ) ], linestyle_opt=opts.LineStyleOpts(curve=0.5), ).set_global_opts( title_opts=opts.TitleOpts(title="Sankey-Level Settings"), tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"), ).render("sankey_with_level_setting.html"))
{"source": "服装", "target": "鞋子", "value": 300}, {"source": "服装", "target": "围巾", "value": 150}, {"source": "服装", "target": "袜子", "value": 50}, {"source": "红包", "target": "同学", "value": 800}, {"source": "红包", "target": "长辈", "value": 500} ] # 桑基图绘图的需求: # 1. 根据开支明细,按照节点和信息流列表结构,直接创建数据的节点和信息流列表; # 2. 绘制桑基图,系列名称为"月度开支" # 3. 数据标签统一放在节点右边 # 4. 保存图片 # 5. 这个图绘制出来肯定特别丑,所以后面还会改进 # 保存路径 resultPath = "./result" if not os.path.exists(path=resultPath): os.mkdir(path=resultPath) # 保存文件名 resultFileName = "purchase_sankey.html" # 执行绘图 sankey = ( Sankey() .add( series_name="月度开支", nodes=nodes, links=links, label_opts=opts.LabelOpts(position="right") ) .render(path=os.path.join(resultPath, resultFileName)) )
import asyncio from aiohttp import TCPConnector, ClientSession import pyecharts.options as opts from pyecharts.charts import Sankey 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() # 获取官方的数据 data = asyncio.run( get_json_data( url="https://echarts.apache.org/examples/data/asset/data/energy.json")) (Sankey(init_opts=opts.InitOpts(width="1600px", height="800px")).add( series_name="", nodes=data["nodes"], links=data["links"], itemstyle_opts=opts.ItemStyleOpts(border_width=1, border_color="#aaa"), linestyle_opt=opts.LineStyleOpts(color="source", curve=0.5, opacity=0.5), tooltip_opts=opts.TooltipOpts(trigger_on="mousemove"), ).set_global_opts(title_opts=opts.TitleOpts( title="Sankey Diagram")).render("Sankey_diagram.html"))
"value": 48 }, { "source": "非遥控", "target": "猛击赛车", "value": 21 }, { "source": "非遥控", "target": "莱肯赛车", "value": 11 }] # 绘制桑基图要求 # 1. 数据系列名称为空 # 2. 添加数据标签放在节点右边; # 3. 全图标题"馆内产品分类"; # 4. 保存图片 # 5. 图片很丑,后面再操心怎么优化 # 保存路径 resultPath = "./result" if not os.path.exists(path=resultPath): os.mkdir(path=resultPath) # 保存文件名 resultFileName = "product_category_sankey.html" # 执行绘图 sankey = (Sankey().set_global_opts(title_opts=opts.TitleOpts( title="馆内产品分类")).add(series_name="", nodes=nodes, links=links, label_opts=opts.LabelOpts(position="right")).render( path=os.path.join(resultPath, resultFileName)))
links = [ {"source": "a", "target": "a1", "value": 5}, {"source": "e", "target": "b", "value": 3}, {"source": "a", "target": "b1", "value": 3}, {"source": "b1", "target": "a1", "value": 1}, {"source": "b1", "target": "c", "value": 2}, {"source": "b", "target": "c", "value": 1}, ] c = ( Sankey() .set_colors(colors) .add( "sankey", nodes=nodes, links=links, pos_bottom="10%", focus_node_adjacency="allEdges", orient="vertical", linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="top"), ) .set_global_opts( title_opts=opts.TitleOpts(title="Sankey-Vertical"), tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"), ) ) c.width = "100%" put_html(c.render_notebook())
#print(all_path) # for element in filter_data1[] for i in all_path: dic = {} dic['name'] = i nodes.append(dic) #print(nodes) # # 生成links links = [] for i in filter_data2.values: dic = {} dic['source'] = i[0] dic['target'] = i[1] dic['value'] = i[2] links.append(dic) #print(links) # pyecharts 所有方法均支持链式调用。 c = ( Sankey() .add( "费用/元", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source",type_="dotted"), label_opts=opts.LabelOpts(position="right",), ) .set_global_opts(title_opts=opts.TitleOpts(title="桑基图")) ) # 输出html可视化结果 c.render('result.html')
""" 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() # 获取官方的数据 data = asyncio.run( get_json_data(url="https://echarts.baidu.com/examples/data/asset/data/energy.json") ) c = ( Sankey() .add( series_name="", nodes=data["nodes"], links=data["links"], itemstyle_opts=opts.ItemStyleOpts(border_width=1, border_color="#aaa"), linestyle_opt=opts.LineStyleOpts(color="source", curve=0.5, opacity=0.5), tooltip_opts=opts.TooltipOpts(trigger_on="mousemove"), ) .set_global_opts(title_opts=opts.TitleOpts(title="Sankey Diagram")) ) c.width = "100%" put_html(c.render_notebook())
resultPath = "./result" if not os.path.exists(path=resultPath): os.mkdir(path=resultPath) # 保存文件名 resultFileName = "pet_sales_sankey.html" # 执行绘图 sankey = ( Sankey(init_opts=opts.InitOpts(theme=ThemeType.ESSOS)) .set_global_opts( title_opts=opts.TitleOpts(title="购买路径"), legend_opts=opts.LegendOpts(is_show=False) ) .add( series_name="", nodes=nodes, links=links, orient="vertical", linestyle_opt=opts.LineStyleOpts( opacity=0.3, curve=0.5, color="target" ), label_opts=opts.LabelOpts( position="top", color="#000000" ) ) ) # 执行保存 sankey.render(path=os.path.join(resultPath, resultFileName))
Sankey(init_opts=opts.InitOpts(width="1000px",height="1200px")) .add( "sankey", nodes=j["nodes"], links=j["links"], pos_top="10%", focus_node_adjacency=True, levels=[ opts.SankeyLevelsOpts( depth=0, itemstyle_opts=opts.ItemStyleOpts(color="#fbb4ae"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=1, itemstyle_opts=opts.ItemStyleOpts(color="#b3cde3"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ), opts.SankeyLevelsOpts( depth=2, itemstyle_opts=opts.ItemStyleOpts(color="#ccebc5"), linestyle_opts=opts.LineStyleOpts(color="source", opacity=0.6), ) ], linestyle_opt=opts.LineStyleOpts(curve=0.5), ) .set_global_opts( title_opts=opts.TitleOpts(title="Tag Sankey-Level"), tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"), )
Parallel, EffectScatter, Polar, Radar, Sankey, Sunburst, ThemeRiver, WordCloud, Timeline, Tree, TreeMap) from pyecharts.faker import Faker from pyecharts.commons.utils import JsCode from pyecharts.globals import WarningType, SymbolType import datetime import random import json # %% [markdown] # ### Sankey with open("data/energy.json") as j: data = json.load(j) sankey = Sankey() sankey.add("", nodes=data["nodes"], links=data["links"]) sankey.render_notebook() # %% [markdown] # ### Sunburst with open("data/drink_flavors.json") as f: data = json.load(f) sunburst = Sunburst() sunburst.add("", data) sunburst.render_notebook() # sunburst.render("output/sunburst.html") # %% [markdown] # ### Graph -- 关系图
nodes = [ {"name": "category1"}, {"name": "category2"}, {"name": "category3"}, {"name": "category4"}, {"name": "category5"}, {"name": "category6"}, ] links = [ {"source": "category1", "target": "category2", "value": 10}, {"source": "category2", "target": "category3", "value": 15}, {"source": "category3", "target": "category4", "value": 20}, {"source": "category5", "target": "category6", "value": 25}, ] c = ( Sankey() .add( "sankey", nodes, links, linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"), label_opts=opts.LabelOpts(position="right"), ) .set_global_opts(title_opts=opts.TitleOpts(title="Sankey-基本示例")) ) c.width = "100%" put_html(c.render_notebook())
nodes.append(dic) links = [] for i in groups.values: dic = {} dic['source'] = i[0] dic['target'] = i[1] dic['value'] = i[2] links.append(dic) pic = Sankey().add( '', #图例名 nodes, #节点数据 links, #边和流量数据 #透明度、弯曲度、颜色 linestyle_opt=opts.LineStyleOpts(opacity=0.3, curve=0.5, color='source'), #标签显示位置 label_opts=opts.LabelOpts(position='right'), #节点之间距离 node_gap=30, ).set_global_opts(title_opts=opts.TitleOpts(title='幸福感指数相关性桑基图')) pic.render('test.html') df['survey_time'] = df['survey_time'].apply(lambda x: int(x[:4])) def split_age(x): if x < 20: return 1 elif x < 40: