Example #1
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 #2
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 #3
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 #4
0
               prior=prior - 1,
               connect=(1, 0),
               alpha=0.5)


fig = plt.figure()
ax = fig.add_subplot(1,
                     1,
                     1,
                     xticks=[],
                     yticks=[],
                     title="Why would you want to do this?\n(But you could.)")
sankey = Sankey(ax=ax, unit=None)
sankey.add(flows=[1, -1],
           orientations=[0, 1],
           patchlabel="0",
           facecolor='k',
           rotation=45)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
sankey.finish()
# Notice:
# 1. The alignment doesn't drift significantly (if at all; with 16007
#    subdiagrams there is still closure).
# 2. The first diagram is rotated 45 deg, so all other diagrams are rotated
#    accordingly.
Example #5
0
# 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)
                    # [gpp1, gpp2, ... rh, ]

sankey.add(flows=soil_flows, 
           fc='brown', label='soil',
           labels=['','','','Rh'],
           orientations=[1, 1, 1, 1],
           #pathlengths=1.0,
           pathlengths=[1.0, 2.0, 3.0, 0.5],
           rotation=0,
           trunklength=1.0
           )


# VEGETATION FLOWS

# INPUTS:
     # pft1, pft2, ...]
gpp = [0.12, 0.35, 0.07]

# OUTPUTS
ra =  [-0.10, -0.05, -0.09]
Example #6
0
 diagrams = sankey.add(
         flows=production_resource_volumes + [-production],
         labels=production_resource_names + [None],
         orientations=[1 if x<num_resources/2 else -1 for x in range(num_resources)] + [0],
         pathlengths=[0.1 for x in range(num_resources)] + [-0.00],
         trunklength=0.2
         
 ).add(
         flows=[imports, production, stock_changes, bunkers, -exports, -losses, -consumption, stat_diffs],
         labels = ['Imports', 'Total Primary\nProduction', 'Stock Changes', 'International\nBunkers', 'Exports', 'Own Use &\nPower Losses', None, 'Statistical\n Differences'],
         orientations=[1, 0, -1, 1, 1, -1, 0, -1],
         pathlengths = [0.2, 0.0, 0.3, 0.3, 0.2, 0.3, -0.2, 0.4],
         trunklength=0.4,
         prior=0,
         connect=(num_resources, 1)
 ).add(
         flows=[consumption, -cons_industry, -cons_transport, -cons_non_energy_use, -cons_other],
         labels=[None, 'Industry', 'Transportation', 'Non-Energy Use', None],
         orientations=[0, 1, 1, -1, 0],
         pathlengths=[0.3, 0.1, 0.1, 0.1, -0.1],
         trunklength=0.2,
         prior=1,
         connect=(6,0), 
 ).add(
         flows=[cons_other, -cons_other_residential, -cons_other_comm_public, -cons_other_other],
         labels=[None, 'Residential', 'Commerce and\nPublic Services', 'Other'],
         orientations=[0, 0, 1, -1],
         pathlengths=[0.1, 0.1, 0.1, 0.1],
         trunklength=0.2,
         prior=2,
         connect=(4,0)
 ).finish()
Example #7
0
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',
           facecolor = '#58A4B0')
diagrams = sankey.finish()
plt.show()
Example #8
0
def test_sankey():
    # lets just create a sankey instance and check the code runs
    sankey = Sankey()
    sankey.add()
Example #9
0
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:
    #    diagram.text.set_fontweight('bold')
    #    diagram.text.set_fontsize('24')
    for text in diagram.texts:
        text.set_fontsize('14')
# Notice that the explicit connections are handled automatically, but the
# implicit ones currently are not.  The lengths of the paths and the trunks
# must be adjusted manually, and that is a bit tricky.

plt.legend(loc='upper right')
Example #10
0
def generate_sankey(title, starting_inflow_unit_count, sankey_outflow_labels,
                    sankey_outflow_proportions, output_pdf_file_path):
    """Use Matplotlib to generate a Sankey diagram of to illustrate results of
    applying criteria to in similarity searching analyses, given a starting
    value (the input unit count), labels for outflows at each step, and the
    proportion of the total number of input units that flow out at each stage
    (in the same order as for the list of labels). Note that the order of the
    outflow labels and corresponding proportions input to this function can be
    re-arranged to reflect the strategy that was applied, without changing this
    function.
    """
    # Check that the outflow proportions all add to no more than 1.
    sum_of_proportions = sum(sankey_outflow_proportions)
    #print('sankey_outflow_proportions:')
    #print(sankey_outflow_proportions)
    #print('sum_of_proportions:')
    #print(sum_of_proportions)
    assert sum_of_proportions >= -1, """Specified outflow proportions for steps
    in the Sankey diagram exceed the total inflow."""

    # Define units.
    #units = '\nsequences'
    units = ''

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

    # Initiate sankey object.
    sankey = Sankey(ax=ax, unit=None)

    # Loop over outflow lists and generate sankey diagram.
    #cur_in = 1.0
    cur_in = 1.0
    count = 0
    for outflow, outflow_label in zip(sankey_outflow_proportions,
                                      sankey_outflow_labels):
        #print('\n')
        #print('outflow_label')
        #print(outflow_label)
        #print('outflow')
        #print(outflow)
        count += 1
        #print('count')
        #print(count)
        if count == 1:
            keep = -(cur_in + outflow)
            #print('keep')
            #print(keep)
            sankey.add(flows=[cur_in, outflow, keep],
                       labels=[str(starting_inflow_unit_count), outflow_label + '\n' +\
                           str(round(outflow*starting_inflow_unit_count)) + units, ''],
                       orientations=[0, -1, 0]
                       )
            cur_in = -(keep)
        else:
            keep = -(cur_in + outflow)
            #print('keep')
            #print(keep)
            kl = ''
            if count == len(sankey_outflow_proportions):
                kl = 'Positive\n' + str(
                    round((cur_in + outflow) *
                          starting_inflow_unit_count)) + units
            sankey.add(flows=[cur_in, outflow, keep],
                       labels=['', outflow_label + '\n' +\
                           str(round(outflow*starting_inflow_unit_count)) + units, kl],
                       orientations=[0, -1, 0],
                       prior=count-2,
                       connect=(2, 0)
                       )
            cur_in = -(keep)

    # Finish the plot.
    diagrams = sankey.finish()
    #plt.legend()
    #plt.show() # This has the advantage of stretching the figure so that the outflow labels are more visible.

    # Write plot to output file path.
    fig.savefig(output_pdf_file_path, bbox_inches='tight')
Example #11
0
def update(k):
    ind = np.argmin(np.abs(k - N_interp))

    line_obj = []
    # Incoming server plots:
    in_comp[0].cla()
    in_comp[1].cla()
    in_stream.cla()
    line_obj.append(in_comp[0].axvline(k, linestyle='--', color='#000000'))

    line_obj.append(in_comp[0].step(N, np.stack(c_traj, axis=2)[0, :, :].T))
    in_comp[0].set_ylabel('In 1: Composition')
    in_comp[0].legend(iter(line_obj[-1]), ('Out 1', 'Out 2'),
                      loc='upper right')
    lines = in_comp[1].step(N, np.stack(c_traj, axis=2)[1, :, :].T)
    line_obj.append(in_comp[1].axvline(k, linestyle='--', color='#000000'))
    in_comp[1].legend(iter(lines), ('Out 1', 'Out 2'), loc='upper right')
    in_comp[1].set_ylabel('In 2: Composition')
    lines = in_stream.step(N, np.concatenate(v_in_traj, axis=1).T)
    line_obj.append(in_stream.axvline(k, linestyle='--', color='#000000'))
    in_stream.legend(iter(lines), ('In 1', 'In 2'), loc='upper right')
    in_stream.set_ylabel('Package stream')

    # Current server plots:
    server_buffer.cla()
    server_load[0].cla()
    server_load[1].cla()
    line_obj.append(server_load[0].axvline(k, linestyle='--', color='#000000'))
    line_obj.append(server_load[1].axvline(k, linestyle='--', color='#000000'))
    line_obj.append(server_buffer.axvline(k, linestyle='--', color='#000000'))
    lines = server_buffer.step(
        N,
        np.concatenate(scheduler_result['s_traj'], axis=1).T)
    server_buffer.legend(iter(lines), ('Out 1', 'Out 2'), loc='upper right')
    server_buffer.set_ylabel('buffer memory')
    server_load[0].step(N, np.concatenate(scheduler_result['bandwidth_traj']))
    server_load[0].set_ylabel('Bandwidth load')
    server_load[1].step(N, np.concatenate(scheduler_result['memory_traj']))
    server_load[1].set_ylabel('Memory load')

    # Outgoing server:
    out_stream.cla()
    out_load[0].cla()
    out_load[1].cla()
    line_obj.append(out_load[0].axvline(k, linestyle='--', color='#000000'))
    line_obj.append(out_load[1].axvline(k, linestyle='--', color='#000000'))
    line_obj.append(out_stream.axvline(k, linestyle='--', color='#000000'))
    line_obj.append(
        out_stream.step(
            N,
            np.concatenate(scheduler_result['v_out_traj'], axis=1).T))
    out_stream.set_ylabel('Package stream')
    out_stream.legend(iter(line_obj[-1]), ('Out 1', 'Out 2'),
                      loc='upper right')
    lines = out_load[0].step(N, np.concatenate(bandwidth_traj, axis=1).T)
    out_load[0].legend(iter(lines), ('Out 1', 'Out 2'), loc='upper right')
    out_load[0].set_ylabel('Bandwidth load')
    lines = out_load[1].step(N, np.concatenate(memory_traj, axis=1).T)
    out_load[1].legend(iter(lines), ('Out 1', 'Out 2'), loc='upper right')
    out_load[1].set_ylabel('Memory load')

    # Sankey Diagrams:
    buffer1_anim.cla()
    buffer2_anim.cla()

    set_x_range = [
        ax.set_ylim([-0.05, 1.05]) for ax in in_comp + server_load + out_load
    ]

    in_mat = (c_traj_interp[ind, :, :] * v_in_traj_interp[[ind]]).T
    out_mat = np.copy(scheduler_result_interp['v_out_traj'][ind])

    in11 = in_mat[0, 0]
    in12 = in_mat[0, 1]
    in21 = in_mat[1, 0]
    in22 = in_mat[1, 1]

    out1 = out_mat[0]
    out2 = out_mat[1]

    mem1 = scheduler_result_interp['s_traj'][ind][0] / 20
    mem2 = scheduler_result_interp['s_traj'][ind][1] / 20

    bw_cap1 = bandwidth_traj_interp[ind][0]
    mem_cap1 = memory_traj_interp[ind][0]

    bw_cap2 = bandwidth_traj_interp[ind][1]
    mem_cap2 = memory_traj_interp[ind][1]

    sankey = Sankey(ax=buffer1_anim, shoulder=0, scale=0.25)
    sankey.add(flows=[in11, in21, -out1],
               labels=['', '', 'Out: 1'],
               orientations=[1, -1, 0],
               pathlengths=[0.5, 0.5, 1])
    buffer1_anim.set_prop_cycle(None)
    sankey.add(flows=[
        in21,
        -in21,
    ],
               labels=['In: 2', ''],
               orientations=[0, 1],
               pathlengths=[0.5, 0.5],
               prior=0,
               connect=(1, 1))
    buffer1_anim.set_prop_cycle(None)
    sankey.add(flows=[
        in11,
        -in11,
    ],
               labels=['In: 1', ''],
               orientations=[0, -1],
               pathlengths=[0.5, 0.5],
               prior=0,
               connect=(0, 1))
    sankey.finish()
    line_obj.append(buffer1_anim.bar(0.5, mem1, width=0.5))
    line_obj.append(buffer1_anim.bar(2.1, bw_cap1, width=0.2))
    line_obj.append(buffer1_anim.bar(2.1, -mem_cap1, width=0.2))
    line_obj.append(
        buffer1_anim.bar(2.1,
                         1,
                         width=0.4,
                         fill=False,
                         edgecolor='k',
                         align='center'))
    line_obj.append(
        buffer1_anim.bar(2.1,
                         -1,
                         width=0.4,
                         fill=False,
                         edgecolor='k',
                         align='center'))
    line_obj.append(buffer1_anim.get_xaxis().set_ticks([]))
    line_obj.append(buffer1_anim.get_yaxis().set_ticks([]))
    line_obj.append(buffer1_anim.set_xlim([-3.3, 3.3]))
    line_obj.append(buffer1_anim.set_ylim([-3.3, 3.3]))

    sankey = Sankey(ax=buffer2_anim, shoulder=0, scale=0.25)
    sankey.add(flows=[in12, in22, -out2],
               labels=['', '', 'Out: 2'],
               orientations=[1, -1, 0],
               pathlengths=[0.5, 0.5, 1])
    buffer2_anim.set_prop_cycle(None)
    sankey.add(flows=[
        in22,
        -in22,
    ],
               labels=['In: 2', ''],
               orientations=[0, 1],
               pathlengths=[0.5, 0.5],
               prior=0,
               connect=(1, 1))
    buffer2_anim.set_prop_cycle(None)
    sankey.add(flows=[
        in12,
        -in12,
    ],
               labels=['In: 1', ''],
               orientations=[0, -1],
               pathlengths=[0.5, 0.5],
               prior=0,
               connect=(0, 1))
    sankey.finish()
    buffer2_anim.bar(0.5, mem2, label='buffer memory', width=0.5)
    buffer2_anim.bar(2.1,
                     bw_cap2,
                     label='bandwidth load',
                     width=0.2,
                     align='center')
    buffer2_anim.bar(2.1,
                     -mem_cap2,
                     label='memory load',
                     width=0.2,
                     align='center')
    buffer2_anim.bar(2.1,
                     1,
                     width=0.4,
                     fill=False,
                     edgecolor='k',
                     align='center')
    buffer2_anim.bar(2.1,
                     -1,
                     width=0.4,
                     fill=False,
                     edgecolor='k',
                     align='center')
    buffer2_anim.legend(loc='lower right')
    buffer2_anim.set_xlim([-3.3, 3.3])
    buffer2_anim.set_ylim([-3.3, 3.3])
    buffer2_anim.get_xaxis().set_ticks([])
    buffer2_anim.get_yaxis().set_ticks([])

    in_comp[0].set_title('Incoming Server')
    server_buffer.set_title('Current Server')
    out_stream.set_title('Outgoing Server')
    buffer1_anim.set_title('Flow Animation')

    return line_obj
Example #12
0
#!/usr/bin/env python
# coding: utf-8

# In[2]:


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

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                     title="Sanky Diagram")
sankey = Sankey(ax=ax, unit=None)
sankey.add(flows=[1.0, -0.3, -0.1, -0.1, -0.5],
           labels=['yamanote', 'keihinn', 'nannboku', 'syounann', ''],
           label='Tokyo Station',
           orientations=[0, -1, 1, 1, 0])
sankey.add(flows=[0.5, 0.1, 0.1, -0.1, -0.1, -0.1, -0.1, -0.3], fc='#37c959',
           label='Sinnzyuku Station',
           labels=['yamanote', 'hukutosinn', 'marunouchi', 'odakyuu', 'sinnzyuku','keiou', 'saikyou', 'chyuuou'],
           orientations=[0, -1, -1, 1, 1, -1, -1, 0], prior=0, connect=(4, 0))
diagrams = sankey.finish()
plt.legend(loc='upper center')
plt.axis('scaled')
plt.show()


# In[ ]:


Example #13
0
    def sankey(self):
        
        import numpy as np
        import matplotlib.pyplot as plt
    
        from matplotlib.sankey import Sankey
        
        P_1_pu = round(self.P_1/self.P_1,5)  
        P_j1_pu = round(self.P_j1/self.P_1,5) 
        P_fe_pu = round(self.P_fe/self.P_1,5) 
        P_j2_pu = round(self.P_j2/self.P_1,5) 
        P_mec_pu = round(self.P_mec/self.P_1,5) 
        P_u_pu = round(self.P_u/self.P_1,3)
        
        s = self.s

        
        
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[] )
        sankey = Sankey(ax=ax, unit=None)
#        sankey.add(flows=[ P_1_pu], labels=['$\sf P_1$'], orientations=[0])
#        sankey.add(flows=[-P_u_pu], labels=['$\sf P_u$'], orientations=[0])
#        sankey.add(flows=[-P_j1_pu], labels=['$\sf P_{j1}$'], orientations=[-1]) 

        if s < 0.001:
            
            P_1_pu = 1.0  
            P_j1_pu = 1.0 *round(self.P_j1/self.P_1,3) 
            P_fe_pu = 1.0 *round(self.P_fe/self.P_1,3) 
            P_j2_pu = 1.0 *round(self.P_j2/self.P_1,3) 
            P_mec_pu = 1.0 *round(self.P_mec/self.P_1,3) 
            P_u_pu = 1.0 *round(self.P_u/self.P_1,3) 
     
            P_j1_pu = self.P_j1/self.P_1 
            P_fe_pu = self.P_fe/self.P_1 
            P_j2_pu = self.P_j2/self.P_1 
            P_mec_pu = self.P_mec/self.P_1 
            P_u_pu =  self.P_u/self.P_1 

            sankey.add(flows=[P_1_pu,-P_mec_pu,-P_j2_pu,-P_fe_pu,-P_j1_pu],
                   labels=['$\sf P_1$',                      
                           '$\sf P_{mec}$',
                            '$\sf P_{J2}$',  
                            '$\sf P_{Fe}$',
                            '$\sf P_{J1}$'],
                    orientations=   [0,  -1,  -1,  -1, -1],
                    pathlengths = [0.2, 0.1, 0.1, 0.1, 0.1]).finish()

        print(s)
        if s >= 0.001:
            
            P_1_pu = 1.0  
            P_j1_pu = 1.0 *round(self.P_j1/self.P_1,3) 
            P_fe_pu = 1.0 *round(self.P_fe/self.P_1,3) 
            P_j2_pu = 1.0 *round(self.P_j2/self.P_1,3) 
            P_mec_pu = 1.0 *round(self.P_mec/self.P_1,3) 
            P_u_pu = 1.0 *round(self.P_u/self.P_1,3) 
     
            P_j1_pu = self.P_j1/self.P_1 
            P_fe_pu = self.P_fe/self.P_1 
            P_j2_pu = self.P_j2/self.P_1 
            P_mec_pu = self.P_mec/self.P_1 
            P_u_pu =  self.P_u/self.P_1 
            
#        if P_u_pu > 0.0000:
            sankey.add(flows=[P_1_pu,-P_mec_pu,-P_j2_pu,-P_fe_pu,-P_j1_pu,-P_u_pu],
                   labels=['$\sf P_1$',                      
                           '$\sf P_{mec}$',
                            '$\sf P_{J2}$',  
                            '$\sf P_{Fe}$',
                            '$\sf P_{J1}$', 
                           '$\sf P_{u}$'],
                    orientations=[0, -1, -1, -1, -1, 0],
                    pathlengths = [0.2, 0.1, 0.1, 0.1, 0.1, 0.3],).finish()
#
#        if P_u_pu < 10000.00001:                     
#            sankey.add(flows=[P_1_pu,-P_mec_pu,-P_j2_pu,-P_fe_pu,-P_j1_pu],
#                   labels=['$\sf P_1$',                      
#                           '$\sf P_{mec}$',
#                            '$\sf P_{j2}$',  
#                            '$\sf P_{fe}$',
#                            '$\sf P_{j1}$'],
#                    orientations=[0, -1, -1, -1, -1],
#                    pathlengths = [0.2, 0.1, 0.1, 0.1, 0.1],).finish
                
        fig.savefig('im_sankey_{:d}.pdf'.format(int(self.n)))
Example #14
0
#   5. Changing the angle of the arrow heads
#   6. Changing the offset between the tips of the paths and their labels
#   7. Formatting the numbers in the path labels and the associated unit
#   8. Changing the appearance of the patch and the labels after the figure is
#      created
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                     title="Flow Diagram of a Widget")


sankey = Sankey(ax=ax, scale=1./25., offset=0.05, head_angle=150,
                format='%.0f', unit='%')
sankey.add(flows=[25, -20, -5],
           labels = ['one', 'two', 'three'],
           orientations=[0,-1,1],
           pathlengths = [0.25, 0.25, 0.25],
           patchlabel="Widget\nA",
           rotation=-90,
           alpha=0.2, lw=2.0) # Arguments to matplotlib.patches.PathPatch()
sankey.add(flows=[20, -10, -10],
           labels = ['', 'four', 'five'],
           orientations=[0,1,1],
           pathlengths = [0.25, 0.25, 0.25],
           patchlabel="Widget\nA",
           rotation=-90,
           prior=0, connect=(1,0),
           alpha=0.2, lw=2.0) # Arguments to matplotlib.patches.PathPatch()
sankey.add(flows=[5, -2.5, -2.5],
           labels = ['', 'six', 'seven'],
           orientations=[0,-1,-1],
           pathlengths = [0.25, 0.25, 0.25],
Example #15
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 #16
0
        mplpyplot.show()
# nodebox section end

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))
sankey.add(patchlabel='\n\nPump 2', facecolor='#37c959',
           flows=[Hdot[14], Hdot[8], -Hdot[9]],
           labels=['Shaft power', '', None],
           pathlengths=[0.4, 0.25, 0.25],
           orientations=[1, 0, 0], prior=1, connect=(3, 1))
sankey.add(patchlabel='Closed\nheater', trunklength=2.914, fc='#37c959',
           flows=[Hdot[9], Hdot[1], -Hdot[11], -Hdot[10]],
           pathlengths=[0.25, 1.543, 0.25, 0.25],
Example #17
0
  tkelabs.append(alltkelabs[i])
  tkeori.append(alltkeori[i])
  tkelen.append(alltkelen[i])
# 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:
#    diagram.text.set_fontweight('bold')
#    diagram.text.set_fontsize('24')
    for text in diagram.texts:
        text.set_fontsize('14')
# Notice that the explicit connections are handled automatically, but the
# implicit ones currently are not.  The lengths of the paths and the trunks
# must be adjusted manually, and that is a bit tricky.

plt.legend(loc='upper right')
suffixes = ['png','pdf']
smallfig = [4.0*9.0/2.2,4.0*6.0/2.2]
for suffix in suffixes:
Example #18
0
#              fontdict=font_title, loc='center')
sankey = Sankey(ax=ax, unit=None, head_angle=90, offset=0.25, shoulder=0.1)

# [0]
# Solar combi system part.
flows_system = [0.8, 0.2, -0.1, -0.1, -0.1, -0.4, -0.3, 0.1]
labels_system = [
    "Production\nsolaire", "Appoint\nElectrique", "Pertes\nechangeur",
    "Pertes\nlineiques", "", "Production de chauffage", "Production\nECS", ""
]
orientations_system = [0, 0, 1, 1, -1, 0, -1, 1]
pathlengths_system = [0.5, 0.5, 0.1, 0.6, 0.5, 0.3, 0.5, 0.5]
sankey.add(flows=flows_system,
           label='Systeme solaire',
           labels=labels_system,
           fc='orange',
           orientations=orientations_system,
           pathlengths=pathlengths_system,
           patchlabel="Systeme solaire\ncombine")

# [1]
# House part.
flows_house = [0.4, 0.3, 0.1, 0.1, 0.1, 0.1, -0.8, -0.1, -0.1]
labels_house = [
    "", "Gains\nSolaires", "", "Equipements", "Occupants", "Eclairage",
    "Besoins thermiques", "Surplus", ""
]
orientations_house = [0, 1, -1, 1, 1, 1, 0, 1, -1]
pathlengths_house = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.2, 0.5, 0.5]
sankey.add(flows=flows_house,
           label='Maison',
Example #19
0
ax = []
for k in range(len(RF)):
    print '\n########################'
    if k == 0:
        print 'Water balance of the whole modelled period:'
        title = "La Mata catchment - Water balance (units in $mm.y^{-1}$)\nWhole modelled period"
    else:        
        print 'Water balance of hydrological year %d/%d:' % (year_lst[k-1], year_lst[k-1] + 1)
        title = "La Mata catchment - Water balance (units in $mm.y^{-1}$)\nHydrological year %d/%d" % (year_lst[k-1], year_lst[k-1] + 1)
    print '\nMMsurf: RF %s, I %s, RFe %s, Esurf %s, DSsurf %s\nMMsoil: Esoil %s, Tsoil %s, ETsoil %s, Ro %s, Rp %s, DSsoil  %s\nUZF: R %s, EXF  %s, DSu %s\nMF: Eg %s, Tg %s, ETg %s,  DRN %s, DSg %s' % (RF[k], I[k], RFe[k], Esurf[k], DSsurf[k], Esoil[k], Tsoil[k], ETsoil[k], Ro[k], Rp[k], DSsoil[k], R[k], EXF[k], DSu[k], Eg[k], Tg[k], ETg[k], DRN[k], DSg[k])
    fig.append(plt.figure()) # figsize=(8.27, 11.7), dpi = 72) 
    ax.append(fig[k].add_subplot(1, 1, 1, xticks=[], yticks=[], title=title))
    pltsankey = Sankey(ax=ax[k], format='%.1F', scale=1.0/1000.0, offset = 0.25)
    pltsankey.add(label='MMsurf', facecolor='lightblue', trunklength = 1,
               flows=[RF[k], -I[k], -RFe[k], DSsurf[k], -Esurf[k]],
               labels=['$RF$', '$I$', '$RFe$',r'$\Delta S_{surf}$', '$E_{surf}$'],
               orientations=[1,1,-1,0,1],
               pathlengths = [0.15, 0.15, 0.15, 0.15, 0.15])
    pltsankey.add(label='MMsoil', facecolor='khaki', trunklength = 1,
               flows=[RFe[k], -Rp[k], -Esoil[k], -Tsoil[k], DSsoil[k], EXF[k], -Ro[k]],
               labels=[None,'$Rp$','$E_{soil}$','$T_{soil}$',r'$\Delta S_{soil}$', None,'$Ro$'],
               orientations=[1,-1,1,1,0,-1,0],
               pathlengths = [0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15],
               prior=0, connect=(2,0))
    pltsankey.add(label='MF_UZF', facecolor='aliceblue', trunklength = 1,
               flows=[Rp[k], -R[k], DSu[k]],
               labels=[None, '$R$', '$\Delta S_u$'],
               orientations=[1, -1, 0],
               pathlengths = [0.15, 0.15, 0.15],
               prior=1, connect=(1, 0))
    pltsankey.add(label='MF_L1', facecolor='MediumSlateBlue', trunklength = 1,
Example #20
0
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

sankey = Sankey()
sankey.add(flows=[1, -1],
       labels=['input', 'output'])
sankey.finish()

Example #21
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 #22
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()
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,
            orientations= [0, -1, -1, 0],
            pathlengths=[0, 2.5, 1, 1],
            trunklength=5.,
            facecolor=tableau20[4],
            label="No Fitness Test"
          ).finish()
Example #24
0
    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%)', ''
    ],
    orientations=[1, 1, 1, -1, -1, -1, 0, 1, 1, 1, -1, -1, -1, 0],
    pathlengths=[
        1.4, 0.8, 0.2, 0.2, 0.8, 1.4, 0.6, 1.4, 0.8, 0.2, 0.2, 0.8, 1.4, 0.6
    ],
    trunklength=2,
    fc=(0.316, 0.758, 0.937, 1),
    ec='k')
plt.text(-2.5, 0, '62,654 Arrivals')
plt.text(1.7, 0, '59,179 Departures')
diagrams = sankey.finish()

#save the figure
                     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!'
           ],
           orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0],
           pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25, 0.25],
           patchlabel="Widget\nA",
           alpha=0.2,
           lw=2.0)  # Arguments pada matplotlib.patches.PathPatch()
diagrams = sankey.finish()
diagrams[0].patch.set_facecolor('#37c959')
diagrams[0].texts[-1].set_color('r')
diagrams[0].text.set_fontweight('bold')
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Dua Sistem")
flows = [0.25, 0.15, 0.60, -0.10, -0.05, -0.25, -0.15, -0.10, -0.35]
sankey = Sankey(ax=ax, unit=None)
sankey.add(flows=flows,
           label='Satu',
           orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0])
Example #26
0
def sankey_of_cyclic_flows(units,title_imported,NBR_sectors,total_inputs,feeding_flows,straight_inputs,total_losses,cycling_losses,straight_losses,useful_outputs,cyclic_array,acyclic_array,self_loops_array,images_directory,file_name):
    fig = plt.figure(figsize=(8, 12))
    #the losses are inferior than the cycles
    max_cycle_flow=np.max(cyclic_array)
    ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title=str(title_imported))
#the scaling is missing because I do not know yet the biggest flow - probably just run a search of maximal value amongst all arrays I use
    sankey = Sankey(ax=ax, format='%.3G', unit=str(units), gap=0.5, scale=1.0/max_cycle_flow)
#create the list of flows for each node in the following order:
    #inputs(positive): feeding_flows, inter-sectoral cycles, self_loop is the last
    #outputs(negative):-self_loop, -cycling_losses,-inter-sectoral cycles
    sankey_flows=[]
    for each_sector in range(NBR_sectors):
        sankey_flows.append(feeding_flows[each_sector])
        for j in range(NBR_sectors):
            if j!=each_sector:           
                sankey_flows.append(cyclic_array[j][each_sector])
        sankey_flows.append(cyclic_array[each_sector][each_sector])        
        sankey_flows.append(-cycling_losses[each_sector])
        for j in range(NBR_sectors):
            if j!=each_sector:
                sankey_flows.append(-cyclic_array[each_sector][j])
        sankey_flows.append(-cyclic_array[each_sector][each_sector])
        
    sankey_labels=[]
    for each_sector in range(NBR_sectors):
         sankey_labels.append('Feeding_flow')
         for j in range(NBR_sectors):
            if j!=each_sector:           
                sankey_labels.append('input from '+str(j))
         sankey_labels.append('Self-loop')       
         sankey_labels.append('Cycling losses')
         for j in range(NBR_sectors):
             if j!=each_sector:           
                sankey_labels.append('output to '+str(j))
         sankey_labels.append('Self-loop')
#create the list of orientations for each flow:
#orientation:
#1 (from/to the top), 0 (from/to the left or right), or -1 (from/to the bottom). 
# If *orientations* == 0, inputs will break in from the left and outputs will break away to the right.
#inputs(positive): feeding_flows:0:horizontal, inter-sectoral cycles:relative, self_loop:1:down 
#outputs(negative):-self_loop:1:down, -cycling_losses:0:horizontal,-inter-sectoral cycles:relative,
    sankey_orientations=[]
    for each_sector in range(NBR_sectors):
         sankey_orientations.append(0)
         for j in range(NBR_sectors):
            if each_sector<j:# 
                sankey_orientations.append(-1)
            if each_sector>j:# 
                sankey_orientations.append(1)
         sankey_orientations.append(-1)
         sankey_orientations.append(0)
         for j in range(NBR_sectors):
             if each_sector<j:# 
                sankey_orientations.append(-1)
             if each_sector>j:# 
                sankey_orientations.append(1)
         sankey_orientations.append(-1)

    sankey_pathlengths=[]
    for each_sector in range(NBR_sectors):
         sankey_pathlengths.append(0.5)#for input
         for j in range(NBR_sectors):
            if each_sector!=j:# 
                sankey_pathlengths.append(2*np.abs(each_sector-j))            
         sankey_pathlengths.append(0.25)#for self-loop
         sankey_pathlengths.append(0.5)#for output
         for j in range(NBR_sectors):
            if each_sector!=j:# 
                sankey_pathlengths.append(2*np.abs(each_sector-j))
         sankey_pathlengths.append(0.25)#for self-loop



#self_loops flows for separate sankey                
    sankey_flows_self_loops=[]
    for each_sector in range(NBR_sectors):
        sankey_flows_self_loops.append(-cyclic_array[each_sector][each_sector])
        sankey_flows_self_loops.append(cyclic_array[each_sector][each_sector])

    sankey_labels_self_loops=[]
    for each_sector in range(NBR_sectors):
        sankey_labels_self_loops.append('Self-loop')
        sankey_labels_self_loops.append('Self-loop')

    sankey_orientations_self_loops=[]
    for each_sector in range(NBR_sectors):
        sankey_orientations_self_loops.append(-1)
        sankey_orientations_self_loops.append(-1)
    sankey_pathlengths_self_loops=[]
    for each_sector in range(NBR_sectors):
        sankey_pathlengths_self_loops.append(0.25)
        sankey_pathlengths_self_loops.append(0.25)
    
#creating the sankey parts representing each node.
#to create the order, the first one does not containt "prior", then the others do.
    for each_sector in range(NBR_sectors):        
        if each_sector==0:
            sankey.add(patchlabel='Sector'+str(each_sector), facecolor='#37c959',
                       flows = sankey_flows[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)],labels = sankey_labels[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], pathlengths = sankey_pathlengths[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], orientations = sankey_orientations[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)])#,prior=2,connect=(5,2) OR ,prior=2,connect=(1,6) OR ,prior=1,connect=(1,5)
        if each_sector==1:      
            sankey.add(patchlabel='Sector'+str(each_sector), facecolor='#37c959', flows = sankey_flows[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], labels =           sankey_labels[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], pathlengths = sankey_pathlengths[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], orientations = sankey_orientations[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)],prior=0,connect=(5,1))
        if each_sector==2:      
            sankey.add(patchlabel='Sector'+str(each_sector), facecolor='#37c959', flows = sankey_flows[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], labels =           sankey_labels[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], pathlengths = sankey_pathlengths[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], orientations = sankey_orientations[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], prior=1,connect=(6,2))
#make a 2 case with if to add the "prior" STOPPED
#        if each_sector>0:      
#             sankey.add(patchlabel='Sector'+str(each_sector), facecolor='#37c959', flows=sankey_flows[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)],            orientations=sankey_orientations[each_sector*(2+2*NBR_sectors):(each_sector+1)*(2+2*NBR_sectors)], prior=each_sector-1, connect=(each_sector,NBR_sectors-each_sector))

#add the self-loop parts
    for each_sector in range(NBR_sectors):      
        sankey.add(patchlabel='Self_loop '+str(each_sector), facecolor='#58b1fa', flows = sankey_flows_self_loops[each_sector*2:(each_sector+1)*2], labels = sankey_labels_self_loops[each_sector*2:(each_sector+1)*2], pathlengths = sankey_pathlengths_self_loops[each_sector*2:(each_sector+1)*2], orientations = sankey_orientations_self_loops[each_sector*2:(each_sector+1)*2], prior = each_sector,connect=(NBR_sectors,0))#,prior=each_sector,connect=(NBR_sectors+1,0)

#add the extra branches to cross connect the sectors



#put the sankey together
    diagrams = sankey.finish()

    #format it
    for diagram in diagrams:
        diagram.text.set_fontweight('bold')
        diagram.text.set_fontsize('10')
        for text in diagram.texts:
            text.set_fontsize('10')
    #pdb.set_trace() #was useful to stop the debug before showin the diagram.
    #plt.show() #use to show the diagram and stop the program.
    
# I HAVE DISABLED SAVING THE SANKEYs BECAUSE I DO NOT NEED IT NOW.
    
    #plt.savefig(images_directory+'/'+file_name+'.png',dpi=300)#If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename.
    
    #THEN I CAN CALL THE image from the main program and insert it in the xls

#def sankey_of_straight_flows():
#    return()
                 edgecolor="#FFFFFF", frameon=True)
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
# ax.set_title(label="Representation des flux du systeme solaire modelise.",
#              fontdict=font_title, loc='center')
sankey = Sankey(ax=ax, unit=None, head_angle=90, offset=0.25, shoulder=0.1)


# [0]
# Solar combi system part.
flows_system = [0.8, 0.2, -0.1, -0.1, -0.1, -0.4, -0.3, 0.1]
labels_system = ["Production\nsolaire", "Appoint\nElectrique", "Pertes\nechangeur", "Pertes\nlineiques",
                 "", "Production de chauffage", "Production\nECS", ""]
orientations_system = [0, 0, 1, 1, -1, 0, -1, 1]
pathlengths_system = [0.5, 0.5, 0.1, 0.6, 0.5, 0.3, 0.5, 0.5]
sankey.add(flows=flows_system, label='Systeme solaire', labels=labels_system, fc='orange',
           orientations=orientations_system, pathlengths=pathlengths_system,
           patchlabel="Systeme solaire\ncombine")


# [1]
# House part.
flows_house = [0.4, 0.3, 0.1, 0.1, 0.1, 0.1, -0.8, -0.1, -0.1]
labels_house = ["", "Gains\nSolaires", "", "Equipements", "Occupants", "Eclairage",
                "Besoins thermiques", "Surplus", ""]
orientations_house = [0, 1, -1, 1, 1, 1, 0, 1, -1]
pathlengths_house = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.2, 0.5, 0.5]
sankey.add(flows=flows_house, label='Maison', labels=labels_house, pathlengths=pathlengths_house,
           orientations=orientations_house, prior=0, connect=(5, 0), fc='#fdf6e3',
           patchlabel="Maison")

# [2]
# 4. Implicitly passing keyword arguments to PathPatch()
# 5. Changing the angle of the arrow heads
# 6. Changing the offset between the tips of the paths and their labels
# 7. Formatting the numbers in the path labels and the associated unit
# 8. Changing the appearance of the patch and the labels after the figure is
#    created

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                     title="Flow Diagram of a Widget")
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=['', '', '', 'First', 'Second', 'Third', 'Fourth',
                   'Fifth', 'Hurray!'],
           orientations=[-1, 1, 0, 1, 1, 1, -1, -1, 0],
           pathlengths=[0.25, 0.25, 0.25, 0.25, 0.25, 0.6, 0.25, 0.25,
                        0.25],
           patchlabel="Widget\nA")  # Arguments to matplotlib.patches.PathPatch()
diagrams = sankey.finish()
diagrams[0].texts[-1].set_color('r')
diagrams[0].text.set_fontweight('bold')

###############################################################################
# Notice:
#
# 1. Since the sum of the flows is nonzero, the width of the trunk isn't
#    uniform.  The matplotlib logging system logs this at the DEBUG level.
# 2. The second flow doesn't appear because its value is zero.  Again, this is
#    logged at the DEBUG level.
Example #29
0
    0.15,
    0.01,
    0.10,
]

# SOIL OUTPUT FLOWS
rh = [-0.65]

soil_flows = np.append(litterfall, rh)
# [gpp1, gpp2, ... rh, ]

sankey.add(
    flows=soil_flows,
    fc='brown',
    label='soil',
    labels=['', '', '', 'Rh'],
    orientations=[1, 1, 1, 1],
    #pathlengths=1.0,
    pathlengths=[1.0, 2.0, 3.0, 0.5],
    rotation=0,
    trunklength=1.0)

# VEGETATION FLOWS

# INPUTS:
# pft1, pft2, ...]
gpp = [0.12, 0.35, 0.07]

# OUTPUTS
ra = [-0.10, -0.05, -0.09]

for pft, val in enumerate(gpp):
        sankey.add(flows=[1, -1], orientations=[1, 1],
                   patchlabel=str(prior+i+1), facecolor=colors.next(),
                   prior=prior+i, connect=(1, 0), alpha=0.5)
def corner(sankey):
    """Generate a corner link.
    """
    prior = len(sankey.diagrams)
    sankey.add(flows=[1, -1], orientations=[0, 1],
               patchlabel=str(prior), facecolor='k',
               prior=prior-1, connect=(1, 0), alpha=0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                     title="Why would you want to do this?\n(But you could.)")
sankey = Sankey(ax=ax, unit=None)
sankey.add(flows=[1, -1], orientations=[0, 1],
           patchlabel="0", facecolor='k',
           rotation=45)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
sankey.finish()
# Notice:
# 1. The alignment doesn't drift significantly (if at all; with 16007
#    subdiagrams there is still closure).
# 2. The first diagram is rotated 45 deg, so all other diagrams are rotated
#    accordingly.
Example #31
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 #32
0
#      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
# circuit since: (1) the lengths of the paths are justified and (2) the
# orientation and ordering of the flows is mirrored.
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")

plt.title("日常生活中成本开支的流量图")

plt.show()
Example #34
0
                     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))
sankey.add(patchlabel='\n\nPump 2',
           facecolor='#37c959',
           flows=[Hdot[14], Hdot[8], -Hdot[9]],
           labels=['Shaft power', '', None],
Example #35
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')
Example #36
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 #37
0
# import matplotlib
# In this section, we first import the necessary matplotlib tools

import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
# We now build a Sankey with an input flow and an output flow of 1. The flows are specified with the flows argument, while labels are provided using labels

sankey = Sankey()
sankey.add(flows=[1,-1],
           labels=['input','output'])
sankey.finish()

# There are others arguments that can be specified. For instance, one can change the orientation of the diagram using the rotation argument
sankey = Sankey()
sankey.add(flows=[1,-1],
           labels=['input','ouput'],
           orientations=[0,0])
sankey.finish()

# Let's go a step further by providing a third flow to our diagram. To do this, we need to specify an orientations argument. In the previous diagram
# we had only tow flows, so by default the Sankey module assumes those to be input and output. Now, we need to specify how the flows align with the diagram
# using a list of orientations. Here, putting an orientation of 1 means it come from the side
sankey=Sankey()
sankey.add(flows=[2,-1,1],
           orientations=[0,0,-1],
           labels=['input','output','second input'],
           rotation=-90)
sankey.finish()

sankey=Sankey()
sankey.add(flows=[1,0.25,-0.25,-0.15,-0.1,-0.1,-0.3,-0.1],