关于python桑葚图的一些实现

前言

最近工作需要,在做用户路径的分析,特此写下该篇文章记录一下
网上主流的桑葚图大概就是如下图所示,我们本篇文章也是还原如下效果

在这里插入图片描述

安装步骤

实现桑葚图,我借用了python的pyecharts组件
pyecharts实际上就是Echarts 与 python 的对接

  1. 安装python,这里不再阐述
  2. 安装pyecharts
pip3 install pyecharts
  1. 安装openpyxl
pip3 install openpyxl

附上官方文档:https://gallery.pyecharts.org/#/README

实现代码


import pandas as pd
from pyecharts.charts import Sankey
from pyecharts import options as opts
import os
from pyecharts.charts import Pie,Bar,Map,Page,Funnel
def get_data(df):
    nodes =[]
    for i in range(2):
        vales=df.iloc[:,i].unique()
        for value in vales:
            dic={}
            dic['name']=value
            nodes.append(dic)
            
    nodes1 = []
    for id in nodes:
        if id not in nodes1:
            nodes1.append(id)
    # print(nodes1)

    links=[]
    for i in df.values:
        dic={}
        dic['source']=i[0]
        dic['target']=i[1]
        dic['value']=i[2]
        links.append(dic)
    return nodes1,links


# print(links)
def get_tu(tablename,df):
    nodes1,links = get_data(df)
    sankey = (
        Sankey(init_opts=opts.InitOpts(width="2000px", height="800px"))
        .add(
            tablename,
            nodes1,
            links,
            pos_top="10%",
            node_width = 30,  #每个桑基图矩形的宽度
            node_gap= 12,  #桑基图中每一列任意两个矩形节点之间的间隔。
            is_draggable = True,
            layout_iterations = 5,

            # focus_node_adjacency=True,
            itemstyle_opts=opts.ItemStyleOpts(border_width=2, border_color="#aaa"),
            linestyle_opt=opts.LineStyleOpts(opacity=0.8, curve=0.5, color='source'),
            label_opts=opts.LabelOpts(position='right'),
        )
        .set_global_opts(title_opts=opts.TitleOpts(title="用户路径分析"))
    )
    return sankey
file ='/Users/superyue/Desktop/tu/user2.xlsx'
df_0826 = pd.read_excel(file,sheet_name='result')
sk1 = get_tu('tets',df_0826)
sk1.render("/Users/superyue/Desktop/tu/test.html")

效果如下:
在这里插入图片描述

总结

如果出现数据丢进去了,程序也运行成功了,但是效果图出不来
那么一定是source和target对应的excel列重复了
以及source或者target列尽量不要出现INT类型的数据(当然也可以通过代码修改)

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值