sankey diagram python dataframe

Solutions on MaxInterview for sankey diagram python dataframe by the best coders in the world

showing results for - "sankey diagram python dataframe"
Gunnar
16 Jan 2018
1# imports
2import pandas as pd
3import numpy as np
4import plotly.graph_objs as go
5from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
6init_notebook_mode(connected=True)
7
8# Nodes & links
9nodes = [['ID', 'Label', 'Color'],
10        [0,'AKJ Education','#4994CE'],
11        [1,'Amazon','#8A5988'],
12        [2,'Flipkart','#449E9E'],
13        [3,'Books','#7FC241'],
14        [4,'Computers & tablets','#D3D3D3'],
15        [5,'Other','#4994CE'],]
16
17# links with your data
18links = [['Source','Target','Value','Link Color'],
19
20        # AKJ
21        [0,3,1,'rgba(127, 194, 65, 0.2)'],
22        [0,4,1,'rgba(127, 194, 65, 0.2)'],
23
24        # Amazon
25        [1,3,1,'rgba(211, 211, 211, 0.5)'],
26        [1,4,1,'rgba(211, 211, 211, 0.5)'],
27        [1,5,1,'rgba(211, 211, 211, 0.5)'],
28
29        # Flipkart
30        [2,5,1,'rgba(253, 227, 212, 1)'],
31        [2,3,1,'rgba(253, 227, 212, 1)'],]
32
33# links with some data for illustrative purposes ################
34#links = [
35#    ['Source','Target','Value','Link Color'],
36#    
37#    # AKJ
38#    [0,3,846888,'rgba(127, 194, 65, 0.2)'],
39#    [0,4,1045,'rgba(127, 194, 65, 0.2)'],
40#    
41#    # Amazon
42#    [1,3,1294423,'rgba(211, 211, 211, 0.5)'],
43#    [1,4,42165,'rgba(211, 211, 211, 0.5)'],
44#    [1,5,415,'rgba(211, 211, 211, 0.5)'],
45#    
46#    # Flipkart
47#    [2,5,1,'rgba(253, 227, 212, 1)'],]
48#################################################################
49
50
51# Retrieve headers and build dataframes
52nodes_headers = nodes.pop(0)
53links_headers = links.pop(0)
54df_nodes = pd.DataFrame(nodes, columns = nodes_headers)
55df_links = pd.DataFrame(links, columns = links_headers)
56
57# Sankey plot setup
58data_trace = dict(
59    type='sankey',
60    domain = dict(
61      x =  [0,1],
62      y =  [0,1]
63    ),
64    orientation = "h",
65    valueformat = ".0f",
66    node = dict(
67      pad = 10,
68    # thickness = 30,
69      line = dict(
70        color = "black",
71        width = 0
72      ),
73      label =  df_nodes['Label'].dropna(axis=0, how='any'),
74      color = df_nodes['Color']
75    ),
76    link = dict(
77      source = df_links['Source'].dropna(axis=0, how='any'),
78      target = df_links['Target'].dropna(axis=0, how='any'),
79      value = df_links['Value'].dropna(axis=0, how='any'),
80      color = df_links['Link Color'].dropna(axis=0, how='any'),
81  )
82)
83
84layout = dict(
85        title = "Draw Sankey Diagram from dataframes",
86    height = 772,
87    font = dict(
88      size = 10),)
89
90fig = dict(data=[data_trace], layout=layout)
91iplot(fig, validate=False)