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()
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 test_format_using_callable(): # test using callable by slightly incrementing above label example def show_three_decimal_places(value): return f'{value:.3f}' s = Sankey(flows=[0.25], labels=['First'], orientations=[-1], format=show_three_decimal_places) assert s.diagrams[0].texts[0].get_text() == 'First\n0.250'
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 createSankey(flows=None, labels=None, orientations=None): '''create simple sankey diagram default example: flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[-1, 1, 0, 1, 1, 1, 0,-1]''' if flows == None: flows = [0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10] if labels == None: labels = ['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'] if orientations == None: orientations = [-1, 1, 0, 1, 1, 1, 0, -1] Sankey(flows=flows, labels=labels, orientations=orientations).finish() plt.title("Sankey diagram with default settings") plt.show()
def sankey_total_sales_by_region(df): # Calculate sales total_sales = sum(df['Sales']) south_sales = df.loc[dataset['Region'] == 'South', 'Sales'].sum() east_sales = df.loc[dataset['Region'] == 'East', 'Sales'].sum() west_sales = df.loc[dataset['Region'] == 'West', 'Sales'].sum() central_sales = df.loc[dataset['Region'] == 'Central', 'Sales'].sum() # Plot Sankey Sankey( flows=[south_sales, east_sales, west_sales, central_sales, -total_sales], labels=['South', 'East', 'West', 'Central', 'Total'], orientations=[0, 0, 1, -1, 0], # fill = False ).finish() plt.title("Total Sales by Region, in $1000") plt.show()
def sankey_total_sales_by_category_in_region_in_year(df,region,year,colour): total_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)), 'Sales'].sum() f_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Furniture')), 'Sales'].sum() o_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Office Supplies')), 'Sales'].sum() t_sales = df.loc[((df['Region'] == region) & (df['order_year'] == year)& (df['Category'] == 'Technology')), 'Sales'].sum() # Sankey Diagram of sales by category in Region in Year Sankey( flows=[f_sales, o_sales, t_sales, -total_sales], # input values & output value with leading minus labels=['Furniture', 'Office Supplies', 'Technology', 'Total'], # labels for all values unit = '$', # units of I/O orientations=[-1, 1, 0, 0], facecolor = colour, head_angle = 120, scale=0.25, rotation=-90, # diagram rotation ).finish() plt.title(str(year)+' :Total Sales by Category in '+region) plt.show()
def sankey_total_sales_by_region_by_year_in_K(df,year): # Calculate sales total_sales = df.loc[df['order_year'] == year, 'Sales'].sum() south_sales = df.loc[((df['Region'] == 'South') & (df['order_year'] == year)), 'Sales'].sum() east_sales = df.loc[((df['Region'] == 'East') & (df['order_year'] == year)), 'Sales'].sum() west_sales = df.loc[((df['Region'] == 'West') & (df['order_year'] == year)), 'Sales'].sum() central_sales = df.loc[((df['Region'] == 'Central') & (df['order_year'] == year)), 'Sales'].sum() # reduce to sales in thousands for cleaner plotting total_sales_K = int(total_sales/1000) south_sales_K = int(south_sales/1000) west_sales_K = int(west_sales/1000) east_sales_K = int(east_sales/1000) central_sales_K = int(central_sales/1000) # Sankey Diagram of sales by Region in Year Sankey( flows=[south_sales_K, east_sales_K, west_sales_K, central_sales_K, -total_sales_K], labels=['South', 'East', 'West', 'Central', 'Total'], orientations=[0, 0, 1, -1, 0] ).finish() plt.title(year+' :Total Sales by Region, in $1000') plt.show()
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Veg and Soil Fluxes") sankey = Sankey(ax=ax, unit=None, tolerance=1e-6, ) # SOIL INPUT FLOWS # pft1 pft2 pft3 litterfall = [0.15, 0.01, 0.10,] # SOIL OUTPUT FLOWS rh = [-0.65] soil_flows = np.append(litterfall, rh) # [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 )
# This demonstrates: # 1. Setting one path longer than the others # 2. Placing a label in the middle of the diagram # 3. Using the the scale argument to normalize the flows # 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=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()
def draw_chart(self): """Plots chart from self.attributes""" if not hasattr(self, "attributes"): return # The first element is always axes data self._setup_axes(self.attributes[0]) for attribute in self.attributes[1:]: series = copy(attribute) # Extract chart type chart_type_string = series.pop("type") x_str, y_str = self.plot_type_xy_mapping[chart_type_string] # Check xdata length if x_str in series and \ len(series[x_str]) != len(series[y_str]): # Wrong length --> ignore xdata series[x_str] = range(len(series[y_str])) else: # Solve the problem that the series data may contain utf-8 data series_list = list(series[x_str]) series_unicode_list = [] for ele in series_list: if isinstance(ele, types.StringType): try: series_unicode_list.append(ele.decode('utf-8')) except Exception: series_unicode_list.append(ele) else: series_unicode_list.append(ele) series[x_str] = tuple(series_unicode_list) fixed_attrs = [] if chart_type_string in self.plot_type_fixed_attrs: for attr in self.plot_type_fixed_attrs[chart_type_string]: # Remove attr if it is a fixed (non-kwd) attr # If a fixed attr is missing, insert a dummy try: fixed_attrs.append(tuple(series.pop(attr))) except KeyError: fixed_attrs.append(()) # Remove contour chart label info from series cl_attrs = {} for contour_label_attr in self.contour_label_attrs: if contour_label_attr in series: cl_attrs[self.contour_label_attrs[contour_label_attr]] = \ series.pop(contour_label_attr) # Remove contourf attributes from series cf_attrs = {} for contourf_attr in self.contourf_attrs: if contourf_attr in series: cf_attrs[self.contourf_attrs[contourf_attr]] = \ series.pop(contourf_attr) if not fixed_attrs or all(fixed_attrs): # Draw series to axes # Do we have a Sankey plot --> build it if chart_type_string == "Sankey": Sankey(self.__axes, **series).finish() else: chart_method = getattr(self.__axes, chart_type_string) plot = chart_method(*fixed_attrs, **series) # Do we have a filled contour? try: if cf_attrs.pop("contour_fill"): cf_attrs.update(series) if "linewidths" in cf_attrs: cf_attrs.pop("linewidths") if "linestyles" in cf_attrs: cf_attrs.pop("linestyles") if not cf_attrs["hatches"]: cf_attrs.pop("hatches") self.__axes.contourf(plot, **cf_attrs) except KeyError: pass # Do we have a contour chart label? try: if cl_attrs.pop("contour_labels"): self.__axes.clabel(plot, **cl_attrs) except KeyError: pass # The legend has to be set up after all series are drawn self._setup_legend(self.attributes[0])
# In[42]: labels = ['', 'Did Not Apply', 'Applied but\nDid Not\nBecome Member' , 'Became\nMember'] labels2 = ['', 'Applied but\nDid Not\nBecome Member', 'Did Not Apply', 'Became\nMember'] plt.close() fig = plt.figure(figsize=(7,7.2), dpi=600, frameon=False) ax = fig.add_subplot(2, 1, 1, xticks=[], yticks=[], frameon=False,) ax.set_title("Flow Diagram of MuscleHub Visitors",y = 1.1, fontweight='bold') ax2 = fig.add_subplot(2,1,2, xticks=[], yticks=[], frameon=False,) sankey = Sankey(ax=ax, scale=0.0005, offset=0.65, head_angle=120, format = '%d', unit=' visitors', gap=1, radius=0.05, shoulder=0.05,) sankey.add(flows = a_flow, labels = labels, orientations= [0, 1, 1, 0], pathlengths=[0, 1, 2.5, 1], trunklength=5., facecolor=tableau20[0], label="Fitness Test" ).finish() sankey2 = Sankey(ax=ax2, scale=0.0005, offset=0.65, head_angle=120, format = '%d', unit=' visitors', gap=1, radius=0.04, shoulder=0.05,) sankey2.add(flows = b_flow, labels = labels2,
source = [n + 1] target = list(range(8)) input_vals = A.row(n) w_min = np.min(input_vals) w = np.log(input_vals) - np.log(w_min) + 0.5 w_T = np.sum(w) values = [w_T] for i in range(len(w)): values.append(-w[i]) labels = ['BB'] for i in range(len(label)): labels.append(label[i]) Sankey(flows=values, labels=labels, offset=3, margin=8, gap=4, shoulder=1, head_angle=130, unit=None, trunklength=30.0, facecolor='lightgreen', edgecolor='lightgreen', alpha=0.8, orientations=[0, 1, 1, 1, 1, 0, -1, -1, -1]).finish() plt.title("Logarithmic Sankey Diagram of Credit Migration Rates") plt.savefig("sankey.png") plt.show()
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)
import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey # basic sankey chart Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("Sankey diagram with default settings")
import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Veg and Soil Fluxes") sankey = Sankey( ax=ax, unit=None, tolerance=1e-6, ) # SOIL INPUT FLOWS # pft1 pft2 pft3 litterfall = [ 0.15, 0.01, 0.10, ] # SOIL OUTPUT FLOWS rh = [-0.65] soil_flows = np.append(litterfall, rh)
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()
'family': 'Source Code Pro'} font_title = {'size': 30, 'family': 'Source Code Pro', 'weight': 'bold'} matplotlib.rcParams['backend.qt4'] = "PySide" matplotlib.rc('font', **font_base) matplotlib.rc('legend', fontsize=20) matplotlib.rc('legend', labelspacing=0.5) # Instanciate a sankey diagram without anything in it. fig = plt.figure(figsize=(24, 12), facecolor="white", 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]
import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey Sankey(flows=[0.50, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['Input', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[0, -1, 1, -1, 1, 0]).finish() plt.title("The default settings produce a diagram like this.") plt.show() #https://matplotlib.org/gallery/api/sankey_basics.html#sphx-glr-gallery-api-sankey-basics-py
# Matius Celcius Sinaga # Ubuntu 14.0 | 32 bit # Python 2.7 # matplotlib-1.4.0 import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'Pertama', 'Kedua', 'Ketiga', 'Keempat', 'Kelima'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("PEngaturan secara umum untuk menghasilkan diagram seperti ini.") fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Diagram alur pada layar") sankey = Sankey(ax=ax, scale=0.01, offset=0.2, head_angle=180, format='%.0f', unit='%') sankey.add(flows=[25, 0, 60, -10, -20, -5, -15, -10, -40], labels=[ '', '', '', 'Pertama', 'Kedua', 'Ketiga', 'Keempat', 'Kelima', 'Ohh.. yeah!' ],
out_vals # In[19]: #create a sankey diagram that shows the 6 largest inflows and outflows for the given station fig = plt.figure(figsize=(13, 9)) ax = fig.add_subplot( 1, 1, 1, xticks=[], yticks=[], title= "Largest Sources and Destinations For Divvy Bikes at Chicago Union Station (2018)" ) sankey = Sankey(ax=ax, unit=None, shoulder=0.1, scale=1, offset=0.35, gap=0.9) sankey.add( flows=[ in1, in2, in3, in4, in5, in6, in_rest, out1, out2, out3, out4, out5, out6, out_rest ], labels=[ 'Michigan & \n Washington \n (6.9%)', 'Columbus & \n Randolph \n (3.6%)', 'Kingsbury & \n Kinzie \n (3.5%)', 'State & \n Randolph \n (3.1%)', 'Michigan & \n Lake \n (3.0%)', 'Larrabee & \n Kingsbury \n (2.7%)', '', 'Michigan & \n Washington \n (6.4%)', 'Larrabee & \n Kingsbury \n (3.2%)', 'Columbus & \n Randolph \n (2.9%)', 'Kingsbury & \n Kinzie \n (2.9%)', 'State & \n Randolph \n (2.1%)', 'State & \n Kinzie \n (2.0%)', '' ],
Demonstrate the Sankey class by producing three basic diagrams. """ import matplotlib.pyplot as plt from matplotlib.sankey import Sankey ############################################################################### # Example 1 -- Mostly defaults # # This demonstrates how to create a simple diagram by implicitly calling the # Sankey.add() method and by appending finish() to the call to the class. Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("The default settings produce a diagram like this.") ############################################################################### # Notice: # # 1. Axes weren't provided when Sankey() was instantiated, so they were # created automatically. # 2. The scale argument wasn't necessary since the data was already # normalized. # 3. By default, the lengths of the paths are justified. ############################################################################### # Example 2
# Sankey plots fig = [] 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],
patchlabel=str(prior+i), facecolor=colors.next(), prior=prior+i-1, connect=(1, 0), alpha=0.5) 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
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()
# Notice: # 1. Since the sum of the flows is nonzero, the width of the trunk isn't # uniform. If verbose.level is helpful (in matplotlibrc), a message is # given in the terminal window. # 2. The second flow doesn't appear because its value is zero. Again, if # verbose.level is helpful, a message is given in the terminal window. # Example 3 # This demonstrates: # 1. Connecting two systems # 2. Turning off the labels of the quantities # 3. Adding a legend fig = plt.figure() ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Flow of Energy") flows = [0.85, -0.40, -0.30, -0.15] sankey = Sankey(ax=ax, unit=None) sankey.add( flows=flows, labels=['', 'Metabolize', ' Activity', '\n\n\n\nGrowth \nand recovery'], label='Metabolize', orientations=[-1, 1, 1, 0]) sankey.add(flows=[-0.85, 1, -0.15], label='Predation', labels=['Net absorption', 'Energy provided \n by food', 'Unused'], orientations=[1, 0, 0], prior=0, connect=(0, 0)) diagrams = sankey.finish() #diagrams[-1].patch.set_hatch('/') plt.legend(loc='best') # Notice that only one connection is specified, but the systems form a
tkeflows.append(alltkeflows[i]) 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]
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))
# -*- coding:utf-8 -*- import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from matplotlib.sankey import Sankey mpl.rcParams["font.sans-serif"]=["FangSong"] mpl.rcParams["axes.unicode_minus"]=False flows=[0.2,0.1,0.4,0.3,-0.6,-0.05,-0.15,-0.2] labels=["","","","","family","trip","education","sport"] orientations=[1,1,0,-1,1,-1,1,0] sankey = Sankey() sankey.add(flows=flows, labels=labels, orientations=orientations, color="c", fc="lightgreen", patchlabel="Life Cost", alpha=0.7) diagrams = sankey.finish() diagrams[0].texts[4].set_color("r") diagrams[0].texts[4].set_weight("bold") diagrams[0].text.set_fontsize(20) diagrams[0].text.set_fontweight("bold")
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=[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
# -*- 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')
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
'd': np.random.randn(50)} data['b'] = data['a'] + 10 * np.random.randn(50) data['d'] = np.abs(data['d']) * 100 plt.scatter('a', 'b', c='c', s='d', data=data) # c=color s = marker size plt.xlabel('entry a') plt.ylabel('entry b') plt.show() #sankey diagram (household budget) from matplotlib.sankey import Sankey fig = plt.figure(figsize = (15,8)) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Household Budget") sankey = Sankey(ax=ax, scale=.1, offset=1, unit='%') sankey.add(flows=[100, -50, -30, -20], labels=['household budget', 'necessities', 'fun', 'saving'], orientations=[0, 0, 1, -1], trunklength = 10, edgecolor = '#027368', facecolor = '#027368') sankey.add(flows=[50, -30, -10, -10], labels=['','rent', 'groceries', 'other'], trunklength = 2, pathlengths = [3,3,3,3], orientations=[0, 1, 0, -1], prior=0, #which sankey are you connecting to (0-indexed) connect=(1, 0), #flow number to connect: (prior, this) edgecolor = '#58A4B0',
size(W, HEIGHT+dy+40) else: def pltshow(mplpyplot): 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))
production_resource_volumes.append(flow.volume) cons_industry = tf.total_into_sector(None, 'Industry', year) cons_transport = tf.total_into_sector(None, 'Transport', year) cons_other = tf.total_into_sector(None, 'Other', year) cons_other_residential = tf.total_into_node(None, 'Residential', year) cons_other_comm_public = tf.total_into_node(None, 'Commerce and public services', year) cons_other_other = cons_other - cons_other_residential - cons_other_comm_public cons_non_energy_use = tf.total_into_sector(None, 'Non-energy use', year) fig = plt.figure(figsize=(8,5), dpi=300) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[]) ax.axis('off') sankey = Sankey(ax=ax, scale=2/norm_const, format='%.1f', unit=' PJ', head_angle=120, margin=0.2, shoulder=0, offset=-0.1, gap=0.15, radius=0.1) 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,
def test_sankey(): # lets just create a sankey instance and check the code runs sankey = Sankey() sankey.add()
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 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')
# 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],