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()
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()
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()
flows=[Hdot[0], -Hdot[16], -Hdot[1], -Hdot[2]], labels=['', None, None, None], pathlengths=[0.25, 0.153, 1.543, 0.25], orientations=[0, 1, -1, -1], prior=5, connect=(4, 0)) sankey.add(patchlabel='\n\n\nReheat', facecolor='#37c959', flows=[Hdot[2], -Hdot[2]], labels=[None, None], pathlengths=[0.725, 0.25], orientations=[-1, 0], prior=6, connect=(3, 0)) sankey.add(patchlabel='Turbine 2', trunklength=3.212, facecolor='#37c959', flows=[Hdot[3], Hdot[16], -Hdot[5], -Hdot[4], -Hdot[17]], labels=[None, 'Shaft power', None, '', 'Shaft power'], pathlengths=[0.751, 0.15, 0.25, 1.93, 0.25], orientations=[0, -1, 0, -1, 1], prior=6, connect=(1, 1)) sankey.add(patchlabel='Condenser', facecolor='#58b1fa', trunklength=1.764, flows=[Hdot[5], -Hdot[18], -Hdot[6]], labels=['', 'Heat rate', None], pathlengths=[0.45, 0.25, 0.883], orientations=[-1, 1, 0], prior=8, connect=(2, 0)) 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') # 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. pltshow(plt)
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
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. plt.show()
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. plt.show() ############################################################################# # # ------------ # # References # """""""""" #
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()
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')
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()
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)
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])
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, flows=[R[k], DSg[k], DRN[k], -EXF[k], ], labels=[None, '$\Delta S_g$', '$DRN$', '$EXF$'], orientations=[1, 0, 1, -1], pathlengths = [0.15, 0.15, 0.15, 0.15], prior=2, connect=(1, 0)) diagrams = pltsankey.finish() diagrams[-1].patch.set_hatch('/') for d in diagrams: for t in d.texts: t.set_fontsize(8) plt.legend(loc='best') leg = plt.gca().get_legend() ltext = leg.get_texts() plt.setp(ltext, fontsize=10) # # 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. if k == 0: print '\nPlot of the whole modelled period done!\n########################' else: print '\nPlot of hydrological year %d/%d done!\n########################' % (year_lst[k-1], year_lst[k-1] + 1)
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: fig.savefig(rootname+"tkeflow."+suffix,bbox=smallfig,bbox_inches='tight',pad_inches=0.01,format=suffix) #plt.show()
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: fig.savefig(rootname + "tkeflow." + suffix, bbox=smallfig,
flows=[Hdot[3], Hdot[16], -Hdot[5], -Hdot[4], -Hdot[17]], labels=[None, 'Shaft power', None, '', 'Shaft power'], pathlengths=[0.751, 0.15, 0.25, 1.93, 0.25], orientations=[0, -1, 0, -1, 1], prior=6, connect=(1, 1)) sankey.add(patchlabel='Condenser', facecolor='#58b1fa', trunklength=1.764, flows=[Hdot[5], -Hdot[18], -Hdot[6]], labels=['', 'Heat rate', None], pathlengths=[0.45, 0.25, 0.883], orientations=[-1, 1, 0], prior=8, connect=(2, 0)) 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') # 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.show() ############################################################################# # # ------------ #
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')
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