Example #1
0
def sankey_diagram():
    sankey = Sankey()
    sankey.add(flows=[2, -4.5, 0.5, 1, 1],
               orientations=[0, 0, 1, -1, 1],
               labels=['input1', 'output', 'input2', 'input3', 'input4'],
               rotation=0)
    sankey.finish()
Example #2
0
def plotSankeyFlow(df, col_1="1", col_2="2"):
    from matplotlib.sankey import Sankey
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(111, title="")
    ax.axis('off')
    df = pd.DataFrame({
        "flow": [242, -121, -121],
        "length": [2, 1, 1],
        "label": ["1", "2", "3"],
        "orientation": [0, 0, 1]
    })
    df1 = pd.DataFrame({
        "flow": [121, -65, -17, -11, -8, -8, -8, -1, -1, -2],
        "path": [2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
        "label": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"],
        "length": [2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
        "orientation": [0, 0, 1, -1, 1, -1, 1, -1, 1, -1]
    })
    sankey = Sankey(ax=ax, scale=0.02, offset=0.3)
    sankey.add(flows=df['flow'],
               pathlengths=df['length'],
               labels=list(df['label']),
               label='1',
               orientations=df['orientation'])
    sankey.add(flows=df1['flow'],
               pathlengths=df1['length'],
               labels=list(df1['label']),
               label='2',
               orientations=df1['orientation'],
               fc='#FFFF00',
               prior=0,
               connect=(1, 0))
    diagrams = sankey.finish()
    plt.legend(loc='lower right')
    plt.show()
Example #3
0
def test_format_using_callable():
    # test using callable by slightly incrementing above label example

    def show_three_decimal_places(value):
        return f'{value:.3f}'

    s = Sankey(flows=[0.25],
               labels=['First'],
               orientations=[-1],
               format=show_three_decimal_places)

    assert s.diagrams[0].texts[0].get_text() == 'First\n0.250'
Example #4
0
def createSankey(flows=None, labels=None, orientations=None):
    '''create simple sankey diagram
        default example:
            flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],
            labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],
            orientations=[-1, 1, 0, 1, 1, 1, 0,-1]'''
    if flows == None:
        flows = [0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10]
    if labels == None:
        labels = ['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth']
    if orientations == None: orientations = [-1, 1, 0, 1, 1, 1, 0, -1]
    Sankey(flows=flows, labels=labels, orientations=orientations).finish()
    plt.title("Sankey diagram with default settings")
    plt.show()
Example #5
0
def displayGraph ( applicationDict ):
    REJECT_STATUS = -1
    DEFAULT_STATUS = 0
    INTERVIEW_STATUS = 1

    numReject = 0
    numGhost = 0
    numInterviews = 0
    totalNumApplications = 0
    statisticsList = []

    for company, applicationList in applicationDict.items ( ):
        for position in applicationList:
            if position.getJobStatus() == REJECT_STATUS:
                numReject += 1
            elif position.getJobStatus() == DEFAULT_STATUS:
                numGhost += 1
            elif position.getJobStatus ( ) == INTERVIEW_STATUS:
                numInterviews += 1
            
    totalNumApplications = numReject + numGhost + numInterviews

    statisticsList.append(-numReject)
    statisticsList.append(-numGhost)
    statisticsList.append (-numInterviews )
    statisticsList.append(totalNumApplications)
            
    print ('\nOpening flowchart display in a new window.' )
    fig = plt.figure()

    subPlot = fig.add_subplot(1,1,1,xticks=[],yticks=[],
                              title='Sankey Diagram - Employment Search 2021')

    myChart = Sankey(ax=subPlot, scale = 0.1, offset=0.25,head_angle=180,
                     format='%.0f', gap = 0.6, radius = 0.3, shoulder = .05,
                     margin = 0.5, unit=' Job applications')

    myChart.add(flows= statisticsList, 
                labels=['Rejected', 'No Response', 'Interviewed', 'Total: '],
                orientations=[0,0,0,0], pathlengths=[0.5,0.5,0.5,0.5],
                trunklength=1.1, facecolor = 'r')

    diagrams = myChart.finish()
    diagrams[0].texts[-1].set_color('b')
    diagrams[0].texts[-1].set_fontweight('bold')
    diagrams[0].text.set_fontweight('bold')

    plt.show()
Example #6
0
def sankey_total_sales_by_region(df):
    # Calculate sales 
    total_sales = sum(df['Sales'])
    south_sales = df.loc[dataset['Region'] == 'South', 'Sales'].sum() 
    east_sales = df.loc[dataset['Region'] == 'East', 'Sales'].sum()
    west_sales = df.loc[dataset['Region'] == 'West', 'Sales'].sum()
    central_sales = df.loc[dataset['Region'] == 'Central', 'Sales'].sum()
    # Plot Sankey 
    Sankey(
        flows=[south_sales, east_sales, west_sales, central_sales, -total_sales],
        labels=['South', 'East', 'West', 'Central', 'Total'],
        orientations=[0, 0, 1, -1, 0],
        # fill = False
           ).finish()
    plt.title("Total Sales by Region, in $1000")
    plt.show()
Example #7
0
def sankey_total_sales_by_category_in_region_in_year(df,region,year,colour):
    total_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)), 'Sales'].sum()
    f_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Furniture')), 'Sales'].sum() 
    o_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Office Supplies')), 'Sales'].sum() 
    t_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Technology')), 'Sales'].sum() 
    
    # Sankey Diagram of sales by category in Region in Year
    Sankey(
        flows=[f_sales, o_sales, t_sales, -total_sales], # input values & output value with leading minus
        labels=['Furniture', 'Office Supplies', 'Technology', 'Total'], # labels for all values
        unit = '$', # units of I/O
        orientations=[-1, 1, 0, 0], 
        facecolor = colour, 
        head_angle = 120,
        scale=0.25, 
        rotation=-90, # diagram rotation
           ).finish()
    plt.title(str(year)+' :Total Sales by Category in '+region)
    plt.show()
Example #8
0
def sankey_total_sales_by_region_by_year_in_K(df,year):
    # Calculate sales
    total_sales = df.loc[df['order_year'] == year, 'Sales'].sum()
    south_sales = df.loc[((df['Region'] == 'South') & (df['order_year'] == year)), 'Sales'].sum() 
    east_sales = df.loc[((df['Region'] == 'East') & (df['order_year'] == year)), 'Sales'].sum()
    west_sales = df.loc[((df['Region'] == 'West') & (df['order_year'] == year)), 'Sales'].sum()
    central_sales = df.loc[((df['Region'] == 'Central') & (df['order_year'] == year)), 'Sales'].sum()

    # reduce to sales in thousands for cleaner plotting
    total_sales_K = int(total_sales/1000)
    south_sales_K = int(south_sales/1000)
    west_sales_K = int(west_sales/1000)
    east_sales_K = int(east_sales/1000)
    central_sales_K = int(central_sales/1000)
    # Sankey Diagram of sales by Region in Year
    Sankey(
        flows=[south_sales_K, east_sales_K, west_sales_K, central_sales_K, -total_sales_K],
        labels=['South', 'East', 'West', 'Central', 'Total'],
        orientations=[0, 0, 1, -1, 0]
           ).finish()
    plt.title(year+' :Total Sales by Region, in $1000')
    plt.show()
Example #9
0
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
from matplotlib import pyplot
from datos import data

d=data('mtcars')
mpg=d.loc["Datsun 710",'mpg']
disp=d.loc["Datsun 710",'disp']
qsec=d.loc["Datsun 710",'qsec']
gear =d.loc["Datsun 710",'gear']
cyl=d.loc["Datsun 710",'cyl']
hp=d.loc["Datsun 710",'hp']

fig, ax = plt.subplots(figsize=(15, 15))

Sankey(ax,margin=10, flows=[disp, mpg,-qsec, -gear, -hp,-cyl,],
       labels=['Displacement\n', 'Miles/(US) gallo', '1/4 Mile Time',
            'Number of forward gears', 'Gross horsepower', 'Number of
cylinders'],
       orientations=[-1, 0, 1, 0, 0, 0]).finish()

ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
plt.title("Datsun 710 Sankey Diagram")
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

# basic sankey chart
Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],
       labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],
       orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()
plt.title("Sankey diagram with default settings")
    source = [n + 1]
    target = list(range(8))
    input_vals = A.row(n)
    w_min = np.min(input_vals)
    w = np.log(input_vals) - np.log(w_min) + 0.5
    w_T = np.sum(w)
    values = [w_T]
    for i in range(len(w)):
        values.append(-w[i])

    labels = ['BB']
    for i in range(len(label)):
        labels.append(label[i])

    Sankey(flows=values,
           labels=labels,
           offset=3,
           margin=8,
           gap=4,
           shoulder=1,
           head_angle=130,
           unit=None,
           trunklength=30.0,
           facecolor='lightgreen',
           edgecolor='lightgreen',
           alpha=0.8,
           orientations=[0, 1, 1, 1, 1, 0, -1, -1, -1]).finish()
    plt.title("Logarithmic Sankey Diagram of Credit Migration Rates")
    plt.savefig("sankey.png")
    plt.show()
# Matius Celcius Sinaga
# Ubuntu 14.0 | 32 bit
# Python 2.7
# matplotlib-1.4.0

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],
       labels=['', '', '', 'Pertama', 'Kedua', 'Ketiga', 'Keempat', 'Kelima'],
       orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()
plt.title("PEngaturan secara umum untuk menghasilkan diagram seperti ini.")
fig = plt.figure()
ax = fig.add_subplot(1,
                     1,
                     1,
                     xticks=[],
                     yticks=[],
                     title="Diagram alur pada layar")
sankey = Sankey(ax=ax,
                scale=0.01,
                offset=0.2,
                head_angle=180,
                format='%.0f',
                unit='%')
sankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40],
           labels=[
               '', '', '', 'Pertama', 'Kedua', 'Ketiga', 'Keempat', 'Kelima',
               'Ohh.. yeah!'
           ],
Example #13
0
fig = plt.figure(figsize=(8, 9))
ax = fig.add_subplot(1,
                     1,
                     1,
                     xticks=[],
                     yticks=[],
                     title="Rankine Power Cycle: Example 8.6 from Moran and "
                     "Shapiro\n\x22Fundamentals of Engineering Thermodynamics "
                     "\x22, 6th ed., 2008")
Hdot = [
    260.431, 35.078, 180.794, 221.115, 22.700, 142.361, 10.193, 10.210, 43.670,
    44.312, 68.631, 10.758, 10.758, 0.017, 0.642, 232.121, 44.559, 100.613,
    132.168
]  # MW
sankey = Sankey(ax=ax, format='%.3G', unit=' MW', gap=0.5, scale=1.0 / Hdot[0])
sankey.add(patchlabel='\n\nPump 1',
           rotation=90,
           facecolor='#37c959',
           flows=[Hdot[13], Hdot[6], -Hdot[7]],
           labels=['Shaft power', '', None],
           pathlengths=[0.4, 0.883, 0.25],
           orientations=[1, -1, 0])
sankey.add(patchlabel='\n\nOpen\nheater',
           facecolor='#37c959',
           flows=[Hdot[11], Hdot[7], Hdot[4], -Hdot[8]],
           labels=[None, '', None, None],
           pathlengths=[0.25, 0.25, 1.93, 0.25],
           orientations=[1, 0, -1, 0],
           prior=0,
           connect=(2, 1))
Example #14
0
    def plot_sankey(self):
        fig = plt.figure(figsize=(15, 10))
        ax = fig.add_subplot(1,
                             1,
                             1,
                             xticks=[],
                             yticks=[],
                             title="Flow Diagram of N")

        Nfluxes = self.dict_sankey
        sankey = Sankey(ax=ax,
                        scale=1. / Nfluxes['total_DIN'],
                        offset=0.1,
                        head_angle=140,
                        format='%.0f',
                        unit='')
        #prior 0
        sankey.add(patchlabel='DIN',
                   facecolor='lightgreen',
                   rotation=180,
                   trunklength=0.25,
                   flows=[
                       Nfluxes['total_DIN'], -Nfluxes['Psm_DIN_uptake'],
                       -Nfluxes['Pmd_DIN_uptake'], -Nfluxes['Plg_DIN_uptake']
                   ],
                   orientations=[0, -1, -1, -1],
                   pathlengths=[0.25, 0.5, 0.26, 0.52],
                   labels=['DIN', None, None, None])
        #prior 1
        sankey.add(patchlabel='Psm N',
                   facecolor='lightgreen',
                   rotation=180,
                   trunklength=0.4,
                   flows=[
                       Nfluxes['Psm_DIN_uptake'], -Nfluxes['Psm_exu_loss'],
                       -Nfluxes['Psm_agg_loss'], -Nfluxes['Zsm_Psm_graz']
                   ],
                   orientations=[1, 1, 1, 0],
                   labels=['Psm\nDIN\nuptake', 'exu', 'agg', None],
                   pathlengths=[0.25, 0.1, 0.7, 0.5],
                   prior=0,
                   connect=(1, 0))
        #prior 2
        sankey.add(patchlabel='Zsm N',
                   facecolor='lightblue',
                   trunklength=0.4,
                   flows=[
                       Nfluxes['Zsm_Psm_graz'], Nfluxes['Zsm_bact_graz'],
                       -Nfluxes['Zsm_DOM_loss'], -Nfluxes['Zmd_Zsm_graz']
                   ],
                   orientations=[0, 1, 1, -1],
                   labels=['Zsm_jprod', 'bact', 'DOM', ''],
                   pathlengths=[0.1, 0.5, 0.1, 0.12],
                   prior=1,
                   connect=(3, 0))
        #prior 3
        sankey.add(patchlabel='Pmd N',
                   facecolor='lightgreen',
                   rotation=180,
                   trunklength=1.0,
                   flows=[
                       Nfluxes['Pmd_DIN_uptake'], -Nfluxes['Pmd_exu_loss'],
                       -Nfluxes['Pmd_agg_loss'], -Nfluxes['Zmd_Pmd_graz']
                   ],
                   orientations=[1, 1, 1, 0],
                   labels=['Pmd\nDIN\nuptake', 'exu', 'agg', None],
                   pathlengths=[0.55, 0.1, 1.35, 0.50],
                   prior=0,
                   connect=(2, 0))
        #prior 4
        sankey.add(patchlabel='Zmd N',
                   facecolor='lightblue',
                   trunklength=.6,
                   flows=[
                       Nfluxes['Zmd_Pmd_graz'], Nfluxes['Zmd_Zsm_graz'],
                       -Nfluxes['Zmd_DOM_loss'], -Nfluxes['Zmd_det_loss'],
                       -Nfluxes['Zlg_Zmd_graz'], -Nfluxes['jhploss_Zmd']
                   ],
                   orientations=[0, 1, 1, 1, -1, -1],
                   labels=['Zmd_jprod', '', 'DOM', 'det', '', 'hp'],
                   pathlengths=[0.4, 0.1, 0.1, 1.0, 0.1, 1.0],
                   prior=2,
                   connect=(3, 1))
        #prior 5
        sankey.add(patchlabel='Plg N',
                   facecolor='lightgreen',
                   rotation=180,
                   trunklength=1.85,
                   flows=[
                       Nfluxes['Plg_DIN_uptake'], -Nfluxes['Plg_exu_loss'],
                       -Nfluxes['Plg_agg_loss'], -Nfluxes['Zlg_Plg_graz']
                   ],
                   orientations=[1, 1, 1, 0],
                   labels=['Plg\nDIN\nuptake', 'exu', 'agg', None],
                   pathlengths=[0.55, 0.1, 2.2, 0.52],
                   prior=0,
                   connect=(3, 0))
        #prior 6
        sankey.add(patchlabel='Zlg N',
                   facecolor='lightblue',
                   trunklength=1.,
                   flows=[
                       Nfluxes['Zlg_Plg_graz'], Nfluxes['Zlg_Zmd_graz'],
                       -Nfluxes['Zlg_DOM_loss'], -Nfluxes['Zlg_det_loss'],
                       -Nfluxes['jhploss_Zlg']
                   ],
                   orientations=[0, 1, 1, 1, -1],
                   labels=['Zmd_jprod', '', 'DOM', 'det', 'hp'],
                   pathlengths=[1.25, 0.1, 0.1, 1.8, 0.5],
                   prior=4,
                   connect=(4, 1))

        sankey.finish()

        #		fig.text(0.60,0.75, 'NPP: {:d}'.format(Nfluxes['NPP']), fontsize=12, fontweight='bold')
        #		fig.text(0.22,0.55, 'mesozooP: {:d}'.format(Nfluxes['mesozooP']), fontsize=12, fontweight='bold')
        #		fig.text(0.25,0.75, 'HPP: {:d}'.format(Nfluxes['hpp']), fontsize=12, fontweight='bold')
        #		fig.text(0.30,0.25, 'Benthic N flux: {:d}'.format(Nfluxes['det_btf']), fontsize=12, fontweight='bold')
        #		fig.text(0.30,0.85, 'Pelagic N flux: {:d}'.format(Nfluxes['det_btf']), fontsize=12, fontweight='bold')
        #		fig.text(0.80,0.87, 'pe-ratio: {:4.2f}'.format(Nfluxes['pe-ratio']), fontsize=12)
        #		fig.text(0.80,0.84, 'z-ratio: {:6.2f}'.format(Nfluxes['z-ratio']), fontsize=12)
        #		fig.text(0.80,0.81, 'f-ratio: {:6.2f}'.format(Nfluxes['f-ratio']), fontsize=12)
        plt.show()
        return None
Example #15
0
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 20:47:03 2016

@author: Paul
"""

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.sankey import Sankey

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                     title="Flow Diagram of Food Waste")
sankey = Sankey(ax=ax, scale=0.01, offset=0.2, head_angle=180,
                format='%.0f', unit='mT')
sankey.add(flows=[22, 19, -3, -3.9, -0.92, -7, -26],
           labels=['Production', 'Import', 'Farm Waste', 'Processing Waste', 'HaFS Waste', 'Consumer Waste', 
                    'Consumer Use'],
           orientations=[0, 1, -1, -1, -1, -1, 0],
           pathlengths=[0.25, 0.25, 0.25, 0.5, 0.25, 0.7,
                        0.25],
           patchlabel="Food Production\nand Waste",
           alpha=0.2, lw=2.0)  # Arguments to matplotlib.patches.PathPatch()
diagrams = sankey.finish()
diagrams[0].patch.set_facecolor('#37c959')
diagrams[0].texts[-1].set_color('b')
diagrams[0].text.set_fontweight('bold')
diagrams[0].texts[4].set_color('r')
diagrams[0].text.set_fontweight('bold')
# -*- coding:utf-8 -*-

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

from matplotlib.sankey import Sankey

mpl.rcParams["font.sans-serif"]=["FangSong"]
mpl.rcParams["axes.unicode_minus"]=False

flows=[0.2,0.1,0.4,0.3,-0.6,-0.05,-0.15,-0.2]
labels=["","","","","family","trip","education","sport"]
orientations=[1,1,0,-1,1,-1,1,0]

sankey = Sankey()

sankey.add(flows=flows,
        labels=labels,
        orientations=orientations,
        color="c",
        fc="lightgreen",
        patchlabel="Life Cost",
        alpha=0.7)

diagrams = sankey.finish()
diagrams[0].texts[4].set_color("r")
diagrams[0].texts[4].set_weight("bold")
diagrams[0].text.set_fontsize(20)
diagrams[0].text.set_fontweight("bold")
Example #17
0
def main(args):
  print "Loading dataset..."
  dsA = nc.Dataset(args.inputfile)
  
  print '(A): ', args.inputfile
  year = args.year
  month = args.month
  cht = args.cohort
  
  numpfts = len(dsA.dimensions['PFTS'])
  
  # needs to have one value per pft
  litterfall = dsA.variables['LTRFALC'][cht,year*month,:]
  
  # needs to be a single value (for whole soil pool)
  rh = dsA.variables['RH'][0,year*month]
  
  # one value per pft
  gpp = dsA.variables['GPP'][cht, year*month,:]
  
  # one value per pft
  npp = dsA.variables['NPP'][cht, year*month, :]
  ra = (npp-gpp)  

  pfts = []
  for i in range(numpfts):
    pfts.append({'gpp': gpp[i],
                 'ltfl': litterfall[i],
                 'Ra': ra[i],
                })
                
  for pft in pfts:
    print pft
  
  fig = plt.figure(figsize=(18,6))
  ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Veg and Soil Fluxes")

  sankey = Sankey(ax=ax, 
                  tolerance=1e-23,
                  #scale=1.00,
                  offset=-1.75,
                  head_angle=130,
                  gap=3.0,
                  radius=0.5,
                  unit='gC/m2',
                  format='%.0f',
                  )
  
  soil_flows = np.append(litterfall, rh)
                      # [gpp1, gpp2, ... rh, ]


  print "litterfall: ", litterfall
  print "rh: ", rh
  print "gpp: ", gpp
  print "ra: ", ra
  print "soil_flows: ", soil_flows

  # make each pft a bit longer
  pathlens = [1+(numpfts-i) for i,x in enumerate(gpp)]
  pathlens.append(0.5) # make the departing rh flow shorter
  
  # make all the pft flows come in from top
  orients = [1 for i in range(len(pathlens))]
  orients[-1] = 0 # change the lasts one (rh) to a side flow
  
  labels = ['pft%s'%i for i, v in enumerate(soil_flows)]
  labels[-1] = 'RH'
  
  sankey.add(patchlabel="Soil",
             flows=soil_flows, 
             fc='brown', label='soil',
             labels=labels,
             orientations=orients,
             #pathlengths=1.0,
             pathlengths=pathlens,
             rotation=0,
             trunklength=7.0,
             )

  print "[PFT ]: gpp    ltrfl    ra"
  for pft, val in enumerate(gpp):
    print "[PFT%s]: %.05f %.05f %.05f"%(pft, gpp[pft], -1.0*litterfall[pft], ra[pft])
  print "-------"
  
#   pft = 1
#   print gpp[pft]
#   print -1.0*litterfall[pft]
#   print ra[pft]
#   
#   sankey.add(flows=[gpp[pft], -1.0*litterfall[pft], ra[pft]], 
#              fc=(0.0, 0.8, 0.0), # rgb 
#              label='pft%s' % (pft),
#              labels=['gpp%s'%pft, 'lf%s'%pft, 'ra%s'%pft,],
#              orientations=[-1,1,0], # 1(top), 0(l/r), -1(bottom)
#                                     # seems to be in relation to prev. diagram...
#              pathlengths=[1,pft*10,1],
#              trunklength=12.0,
#              prior=0, connect=(pft,1)
#              )

  # VEGETATION FLOWS
  for pft, val in enumerate(gpp):
    if (-1.0*litterfall[pft] < 0) or (-1.0*litterfall[pft] > 0):
    
      sankey.add(flows=[gpp[pft], -1.0*litterfall[pft], ra[pft]], 
                 fc=(0.0, 0.8, 0.0), # rgb 
                 label='pft%s' % (pft),
                 labels=['gpp%s'%pft, 'lf%s'%pft, 'ra%s'%pft,],
                 orientations=[-1,1,-1], # 1(top), 0(l/r), -1(bottom)
                                        # seems to be in relation to prev. diagram...
                 #pathlengths=[1,pft+10,1],
                 trunklength=12.0,
                 prior=0, connect=(pft,1)
                 )
    else:
     pass
#       sankey.add(flows=[gpp[pft], -1.0*litterfall[pft], ra[pft]], 
#                  fc=(0.0, 0.8, 0.0), # rgb 
#                  label='pft%s' % (pft),
#                  labels=['gpp%s'%pft, 'lf%s'%pft, 'ra%s'%pft,],
#                  orientations=[-1,1,-1], # 1(top), 0(l/r), -1(bottom)
#                                         # seems to be in relation to prev. diagram...
#                  pathlengths=[1,6,1],
#                  #trunklength=2.0,
#                  #prior=0, connect=(pft,1)
#                  )

  diagrams = sankey.finish()
  #print diagrams
  #diagrams[-1].patch.set_hatch('/')  
  plt.legend(loc='best')
  plt.title("The default settings produce a diagram like this.")




  wrapup(args)
Example #18
0
def sankey_drawings():
    """ Draw sanky diagrams for the figures """
    from matplotlib import pyplot as plt
    from matplotlib.sankey import Sankey

    fig = plt.figure(figsize=(12, 8))
    ax = fig.add_subplot(
        1,
        1,
        1,
        xticks=[],
        yticks=[],
        title=
        "Statistics from the 2nd edition of\nfrom Audio Signal Processing for Music Applications by Stanford University\nand Universitat Pompeu Fabra of Barcelona on Coursera (Jan. 2016)"
    )
    learners = [14460, 9720, 7047, 3059, 2149, 351]
    labels = [
        "Total learners joined", "Learners that visited the course",
        "Learners that watched a lecture", "Learners that browsed the forums",
        "Learners that submitted an exercise",
        "Learners that obtained a grade >70%\n(got a Statement of Accomplishment)"
    ]
    colors = ["#FF0000", "#FF4000", "#FF8000", "#FFBF00", "#FFFF00"]

    sankey = Sankey(ax=ax, scale=0.0015, offset=0.3)
    for input_learner, output_learner, label, prior, color in zip(
            learners[:-1], learners[1:], labels, [None, 0, 1, 2, 3], colors):
        if prior != 3:
            sankey.add(flows=[
                input_learner, -output_learner, output_learner - input_learner
            ],
                       orientations=[0, 0, 1],
                       patchlabel=label,
                       labels=['', None, 'quit'],
                       prior=prior,
                       connect=(1, 0),
                       pathlengths=[0, 0, 2],
                       trunklength=10.,
                       rotation=0,
                       facecolor=color)
        else:
            sankey.add(flows=[
                input_learner, -output_learner, output_learner - input_learner
            ],
                       orientations=[0, 0, 1],
                       patchlabel=label,
                       labels=['', labels[-1], 'quit'],
                       prior=prior,
                       connect=(1, 0),
                       pathlengths=[0, 0, 10],
                       trunklength=10.,
                       rotation=0,
                       facecolor=color)
    diagrams = sankey.finish()
    for diagram in diagrams:
        diagram.text.set_fontweight('bold')
        diagram.text.set_fontsize('10')
        for text in diagram.texts:
            text.set_fontsize('10')
    ylim = plt.ylim()
    plt.ylim(ylim[0] * 1.05, ylim[1])
Example #19
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

fig = plt.figure()
ax = fig.add_subplot(1,
                     1,
                     1,
                     xticks=[],
                     yticks=[],
                     title="Veg and Soil Fluxes")

sankey = Sankey(
    ax=ax,
    unit=None,
    tolerance=1e-6,
)

# SOIL INPUT FLOWS
# pft1  pft2  pft3
litterfall = [
    0.15,
    0.01,
    0.10,
]

# SOIL OUTPUT FLOWS
rh = [-0.65]

soil_flows = np.append(litterfall, rh)
Example #20
0
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.sankey import Sankey

Sankey(flows=[0.50, -0.20, -0.15, -0.05, -0.50, -0.10],
       labels=['Input', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],
       orientations=[0, -1, 1, -1, 1, 0]).finish()
plt.title("The default settings produce a diagram like this.")
plt.show()

#https://matplotlib.org/gallery/api/sankey_basics.html#sphx-glr-gallery-api-sankey-basics-py
Example #21
0
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data) # c=color s = marker size
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()


#sankey diagram (household budget)
from matplotlib.sankey import Sankey
fig = plt.figure(figsize = (15,8))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], 
                     title="Household Budget")
sankey = Sankey(ax=ax, scale=.1, offset=1, unit='%')
sankey.add(flows=[100, -50, -30, -20],
           labels=['household budget', 'necessities', 'fun', 
                   'saving'],
           orientations=[0, 0, 1, -1],
           trunklength = 10,
           edgecolor = '#027368',
           facecolor = '#027368')
sankey.add(flows=[50, -30, -10, -10], 
           labels=['','rent', 'groceries', 'other'],
           trunklength = 2,
           pathlengths = [3,3,3,3],
           orientations=[0, 1, 0, -1], 
           prior=0, #which sankey are you connecting to (0-indexed)
           connect=(1, 0), #flow number to connect: (prior, this)
           edgecolor = '#58A4B0',
Example #22
0
    def draw_chart(self):
        """Plots chart from self.attributes"""

        if not hasattr(self, "attributes"):
            return

        # The first element is always axes data
        self._setup_axes(self.attributes[0])

        for attribute in self.attributes[1:]:

            series = copy(attribute)
            # Extract chart type
            chart_type_string = series.pop("type")

            x_str, y_str = self.plot_type_xy_mapping[chart_type_string]
            # Check xdata length
            if x_str in series and \
               len(series[x_str]) != len(series[y_str]):
                # Wrong length --> ignore xdata
                series[x_str] = range(len(series[y_str]))
            else:
                # Solve the problem that the series data may contain utf-8 data
                series_list = list(series[x_str])
                series_unicode_list = []
                for ele in series_list:
                    if isinstance(ele, types.StringType):
                        try:
                            series_unicode_list.append(ele.decode('utf-8'))
                        except Exception:
                            series_unicode_list.append(ele)
                    else:
                        series_unicode_list.append(ele)
                series[x_str] = tuple(series_unicode_list)

            fixed_attrs = []
            if chart_type_string in self.plot_type_fixed_attrs:
                for attr in self.plot_type_fixed_attrs[chart_type_string]:
                    # Remove attr if it is a fixed (non-kwd) attr
                    # If a fixed attr is missing, insert a dummy
                    try:
                        fixed_attrs.append(tuple(series.pop(attr)))
                    except KeyError:
                        fixed_attrs.append(())

            # Remove contour chart label info from series
            cl_attrs = {}
            for contour_label_attr in self.contour_label_attrs:
                if contour_label_attr in series:
                    cl_attrs[self.contour_label_attrs[contour_label_attr]] = \
                        series.pop(contour_label_attr)

            # Remove contourf attributes from series
            cf_attrs = {}
            for contourf_attr in self.contourf_attrs:
                if contourf_attr in series:
                    cf_attrs[self.contourf_attrs[contourf_attr]] = \
                        series.pop(contourf_attr)

            if not fixed_attrs or all(fixed_attrs):
                # Draw series to axes

                # Do we have a Sankey plot --> build it
                if chart_type_string == "Sankey":
                    Sankey(self.__axes, **series).finish()

                else:
                    chart_method = getattr(self.__axes, chart_type_string)
                    plot = chart_method(*fixed_attrs, **series)

                # Do we have a filled contour?
                try:
                    if cf_attrs.pop("contour_fill"):
                        cf_attrs.update(series)
                        if "linewidths" in cf_attrs:
                            cf_attrs.pop("linewidths")
                        if "linestyles" in cf_attrs:
                            cf_attrs.pop("linestyles")
                        if not cf_attrs["hatches"]:
                            cf_attrs.pop("hatches")
                        self.__axes.contourf(plot, **cf_attrs)
                except KeyError:
                    pass

                # Do we have a contour chart label?
                try:
                    if cl_attrs.pop("contour_labels"):
                        self.__axes.clabel(plot, **cl_attrs)
                except KeyError:
                    pass

        # The legend has to be set up after all series are drawn
        self._setup_legend(self.attributes[0])
Demonstrate the Sankey class by producing three basic diagrams.
"""

import matplotlib.pyplot as plt

from matplotlib.sankey import Sankey


###############################################################################
# Example 1 -- Mostly defaults
#
# This demonstrates how to create a simple diagram by implicitly calling the
# Sankey.add() method and by appending finish() to the call to the class.

Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],
       labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'],
       orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()
plt.title("The default settings produce a diagram like this.")

###############################################################################
# Notice:
#
# 1. Axes weren't provided when Sankey() was instantiated, so they were
#    created automatically.
# 2. The scale argument wasn't necessary since the data was already
#    normalized.
# 3. By default, the lengths of the paths are justified.


###############################################################################
# Example 2
Example #24
0
# Set the flow diagram Geometry
tketrun = 3
# Common Snake properties
if len(sys.argv) > 2:
    tkelabel = sys.argv[3]
else:
    tkelabel = "Stratified Turbulence"
#
rot = 0
fcol = "#DFDFDF"
#
snakey = Sankey(ax=ax,
                format='%4.0f',
                unit=r'$\mathrm{nW/kg}$',
                margin=.5,
                offset=-.5,
                radius=.125,
                gap=.125,
                scale=10.0 / maxflow,
                head_angle=120)
snakey.add(flows=tkeflows,
           orientations=tkeori,
           pathlengths=tkelen,
           labels=tkelabs,
           rotation=rot,
           trunklength=tketrun,
           facecolor=fcol,
           label=tkelabel)
#
diagrams = snakey.finish()
for diagram in diagrams:
Example #25
0
# Notice:
#   1. Since the sum of the flows is nonzero, the width of the trunk isn't
#      uniform.  If verbose.level is helpful (in matplotlibrc), a message is
#      given in the terminal window.
#   2. The second flow doesn't appear because its value is zero.  Again, if
#      verbose.level is helpful, a message is given in the terminal window.

# Example 3
# This demonstrates:
#   1. Connecting two systems
#   2. Turning off the labels of the quantities
#   3. Adding a legend
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Flow of Energy")
flows = [0.85, -0.40, -0.30, -0.15]
sankey = Sankey(ax=ax, unit=None)
sankey.add(
    flows=flows,
    labels=['', 'Metabolize', '  Activity', '\n\n\n\nGrowth \nand recovery'],
    label='Metabolize',
    orientations=[-1, 1, 1, 0])
sankey.add(flows=[-0.85, 1, -0.15],
           label='Predation',
           labels=['Net absorption', 'Energy provided \n by food', 'Unused'],
           orientations=[1, 0, 0],
           prior=0,
           connect=(0, 0))
diagrams = sankey.finish()
#diagrams[-1].patch.set_hatch('/')
plt.legend(loc='best')
# Notice that only one connection is specified, but the systems form a
Example #26
0
out_vals

# In[19]:

#create a sankey diagram that shows the 6 largest inflows and outflows for the given station
fig = plt.figure(figsize=(13, 9))
ax = fig.add_subplot(
    1,
    1,
    1,
    xticks=[],
    yticks=[],
    title=
    "Largest Sources and Destinations For Divvy Bikes at Chicago Union Station (2018)"
)
sankey = Sankey(ax=ax, unit=None, shoulder=0.1, scale=1, offset=0.35, gap=0.9)
sankey.add(
    flows=[
        in1, in2, in3, in4, in5, in6, in_rest, out1, out2, out3, out4, out5,
        out6, out_rest
    ],
    labels=[
        'Michigan & \n Washington \n (6.9%)',
        'Columbus & \n Randolph \n (3.6%)', 'Kingsbury & \n Kinzie \n (3.5%)',
        'State & \n Randolph \n (3.1%)', 'Michigan & \n Lake \n (3.0%)',
        'Larrabee & \n Kingsbury \n (2.7%)', '',
        'Michigan & \n Washington \n (6.4%)',
        'Larrabee & \n Kingsbury \n (3.2%)',
        'Columbus & \n Randolph \n (2.9%)', 'Kingsbury & \n Kinzie \n (2.9%)',
        'State & \n Randolph \n (2.1%)', 'State & \n Kinzie \n (2.0%)', ''
    ],
Example #27
0
def test_sankey():
    # lets just create a sankey instance and check the code runs
    sankey = Sankey()
    sankey.add()
# In[42]:

labels = ['', 'Did Not Apply', 'Applied but\nDid Not\nBecome Member' , 'Became\nMember']
labels2 = ['', 'Applied but\nDid Not\nBecome Member', 'Did Not Apply', 'Became\nMember']

plt.close()


fig = plt.figure(figsize=(7,7.2), dpi=600, frameon=False)

ax = fig.add_subplot(2, 1, 1, xticks=[], yticks=[], frameon=False,)
ax.set_title("Flow Diagram of MuscleHub Visitors",y = 1.1, fontweight='bold')
ax2 = fig.add_subplot(2,1,2, xticks=[], yticks=[], frameon=False,)

sankey = Sankey(ax=ax, scale=0.0005, offset=0.65, head_angle=120,
                format = '%d', unit=' visitors', gap=1, 
                radius=0.05, shoulder=0.05,)
sankey.add(flows = a_flow,
            labels = labels,
            orientations= [0, 1, 1, 0],
            pathlengths=[0, 1, 2.5, 1],
            trunklength=5.,
            facecolor=tableau20[0],
            label="Fitness Test"
          ).finish()

sankey2 = Sankey(ax=ax2, scale=0.0005, offset=0.65, head_angle=120,
                format = '%d', unit=' visitors', gap=1, 
                radius=0.04, shoulder=0.05,)
sankey2.add(flows = b_flow,
            labels = labels2,
Example #29
0
    def qc_sankey_diagram_speed(self,
                                stations='all',
                                wind_speed='vw10m(m/s)',
                                scale=10):
        from matplotlib.sankey import Sankey
        import matplotlib.pylab as pl

        time_series = self.p.observation.time_series

        if stations == 'all':
            scale = 0.0000001
        else:
            time_series = time_series[time_series["name"].isin(stations)]
            scale = 0.0000001 * scale

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=None)

        sankey = Sankey(ax=ax,
                        scale=scale,
                        offset=0.2,
                        head_angle=135,
                        format="%i",
                        unit=' ')

        all_speeds = time_series[wind_speed].count()
        qc_1 = time_series[wind_speed][
            time_series["qc_1_speed"] != 1].dropna().count()
        qc_2 = time_series[wind_speed][(time_series["qc_1_speed"] == 1) & (
            time_series["qc_2_speed"] != 1)].dropna().count()
        qc_3 = time_series[wind_speed][
            (time_series["qc_1_speed"] == 1) & (time_series["qc_2_speed"] == 1)
            & (time_series["qc_3_speed"] != 1)].dropna().count()
        qc_5 = time_series[wind_speed][
            (time_series["qc_1_speed"] == 1) & (time_series["qc_2_speed"] == 1)
            & (time_series["qc_3_speed"] == 1) &
            (time_series["qc_5_speed"] != 1)].dropna().count()
        qc_6 = time_series[wind_speed][
            (time_series["qc_1_speed"] == 1) & (time_series["qc_2_speed"] == 1)
            & (time_series["qc_3_speed"] == 1) &
            (time_series["qc_5_speed"] == 1) &
            (time_series["qc_6_speed"] != 1)].dropna().count()

        colors = pl.cm.cividis(np.linspace(0, 1, 5))

        result_1 = (all_speeds - qc_1)
        sankey.add(flows=[all_speeds, -qc_1, -result_1],
                   labels=['All data', 'Unphysical values', None],
                   orientations=[0, -1, 0],
                   facecolor=colors[0])

        # Arguments to matplotlib.patches.PathPatch
        result_2 = result_1 - qc_2
        sankey.add(flows=[result_1, -qc_2, -result_2],
                   labels=[None, "Excessive miss", None],
                   orientations=[0, 1, 0],
                   prior=0,
                   connect=(2, 0),
                   facecolor=colors[1])

        result_3 = result_2 - qc_3
        sankey.add(flows=[result_2, -qc_3, -result_3],
                   labels=[None, "Constant sequences", None],
                   orientations=[0, -1, 0],
                   prior=1,
                   connect=(2, 0),
                   facecolor=colors[2])

        result_4 = result_3 - qc_5
        sankey.add(flows=[result_3, -qc_5, -result_4],
                   labels=[None, "High variability", None],
                   orientations=[0, 1, 0],
                   prior=2,
                   connect=(2, 0),
                   facecolor=colors[3])

        result_5 = result_4 - qc_6
        sankey.add(flows=[result_4, -qc_6, -result_5],
                   labels=[None, "Bias", "Valid observations"],
                   orientations=[0, -1, 0],
                   prior=3,
                   connect=(2, 0),
                   facecolor=colors[4])

        diagrams = sankey.finish()
        diagrams[0].texts[-1].set_color('r')
        diagrams[0].text.set_fontweight('bold')
Example #30
0
def group_composition_sankey(names_and_networks,
                             project_name,
                             kind='years',
                             directory=plots_dir):
    flows = compute_developer_flows(names_and_networks, project_name)
    years = python_years if project_name == 'python' else debian_years
    labels = years
    color_map = cm.get_cmap('Dark2', len(years))
    colors = [color_map(i) for i in range(len(years))]
    # Plot
    fig = plt.figure(figsize=(20, 14))
    title = "Python developer mobility in the top connectivity level"
    ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=title)
    sankey = Sankey(ax=ax, scale=0.35, offset=1)
    last = None
    previous_id = 0
    #for i, flow in enumerate(flow for flow in flows if any(flow)):
    for i, flow in enumerate(flows):
        if not any(flow):
            continue
        if last is None:  # First group
            sankey.add(flows=flow,
                       fc=colors[i],
                       label=str(labels[i]),
                       orientations=[0, 0])
            last = flow
            previous_id += 1
        else:
            sankey.add(
                flows=flow,
                fc=colors[i],
                label=str(labels[i]),
                orientations=[0, 1, -1, 0],
                labels=[None, '', '', ''],
                #pathlengths=[0.5, 1.75, 1.75, 0.5],
                pathlengths=[1, 2, 2, 1],
                prior=previous_id - 1,
                connect=(3, 0) if len(last) == 4 else (1, 0))
            last = flow
            previous_id += 1
    diagrams = sankey.finish()
    for diagram in diagrams:
        diagram.text.set_fontweight('bold')
        #diagram.text.set_fontsize('small')
        #for text in diagram.texts:
        #    text.set_fontsize('small')
    #leg = plt.legend(loc='best')
    leg = ax.legend(bbox_to_anchor=(1, 0.1),
                    ncol=8,
                    fancybox=True,
                    shadow=True)
    #for t in leg.get_texts():
    #    t.set_fontsize('small')
    if directory is None:
        plt.ion()
        plt.show()
    else:
        fname = os.path.join(
            directory, 'sankey_mobility_{}_{}'.format(project_name, kind))
        plt.savefig("{}.eps".format(fname))
        plt.savefig("{}.png".format(fname))
        plt.close()