[PYTHON] (Personal note) Sankey diagram

Purpose of this article

Create a sankey-diagram like the one below. {0,1} represents two types of events, and assuming that multiple events occur in a certain period, such as 0-> 1-> 1, the transition of the event occurrence is The purpose is to visualize.

image.png

Preparation

import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 100)
import random

import warnings
warnings.filterwarnings('ignore')

Dummy data preparation

n=100

agent = [random.choice([1,2,3,4,5,6,7,8,9,10]) for i in range(n)]
day = [random.choice([1,2,3,4,5]) for i in range(n)]
time = [random.random() for i in range(n)]
event = [random.choice([0,1]) for i in range(n)]


df = pd.DataFrame({"agent":agent,
                   "day":day,
                   "time":time,
                   "event":event})

df = df.sort_values(["day","time"])

summary = df.groupby(["agent", "day"])["event"].apply(lambda x: [str(xi) for xi in x]).apply(''.join).reset_index()
summary.head()

image.png

How an agent(human or machine) triggered an event during a period ofday ʻevent Is the data.

max_len_event = max([len(i) for i in summary["event"]])
max_len_event
>>5
summary["event"] = ["{0:-<5}".format(i) for i in summary["event"]]
summary.head()

image.png

value_list = []

for i in range(max_len_event-1):
    tmp = [ei[i:(i+2)] for ei in summary["event"]]

    #0->0
    n = sum([1 if ei=="00" else 0 for ei in tmp])
    value_list.append(n)

    #0->1
    n = sum([1 if ei=="01" else 0 for ei in tmp])
    value_list.append(n)

    #1->0
    n = sum([1 if ei=="10" else 0 for ei in tmp])
    value_list.append(n)

    #1->1
    n = sum([1 if ei=="11" else 0 for ei in tmp])
    value_list.append(n)

source_list = [[i, i] for i in range(max_len_event*2-2)]
source_list = np.array(source_list).flatten()

target_list = [[i, i+1, i, i+1] for i in range(2, max_len_event*2, 2)]
target_list = np.array(target_list).flatten()

label_list = ["0", "1"] * max_len_event
import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label =  label_list,
      color = "blue"
    ),
    link = dict(
      source = source_list,
      target = target_list,
      value = value_list
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

image.png

that's all!

reference

Qiita: [Python] What do you do with visualization of 4 or more variables? Plotly:Sankey Diagram in Python

Recommended Posts

(Personal note) Sankey diagram
Completely personal note
Flask's personal note # 2
Flask's personal note # 1
[AtCoder] ABC165C Personal Note [Python]
Note
Note
Deploy Django api on heroku (personal note)
[Personal note] Web page scraping with python3
Personal Note Package to install on Anaconda