栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

关于python桑葚图的一些实现

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于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类型的数据(当然也可以通过代码修改)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977113.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号