After the *JSON* files have been created, they are used as input for generating the *Sankey* diagrams. Using the *HTML* library, we can display a snippet of the final website below. The driving logic of the *HTML* is as follows: the main *Javascript* function change
loads the corresponding *JSON* based on the *country* and *year* selections into the sankey
variable. All data is loaded asynchronously, on-demand. A modified version on the the *Sankey* module of *D3.js* creates the nodes and links from the data and displays the diagram as *Scalable Vector Graphics (SVG)* elements onto the browser's canvas, defined in the svg
variable. Upon a change in the data source, the size parameters of the SVG elements are modified and elements are added or removed, as necessary. Upon hover over a node or a link, the updatepie
function displays the corresponding the pie chart, using information from the *supply* field of the *JSON* data. Please view the *HTML* source of the project website for a thorough understanding of the canvas painting process. The diagram usage instructions are briefly presented here:
# 3.2. World Map & Plotting tools
# After the *JSON* files have been created, they are used as input for generating the *Sankey* diagrams. Using the *HTML* library, we can display
# data preparation
# In[35]:
#food weight
wrowi_bycountry={}
wrowi_raw_bycountry={}
wrowi_aec_bycountry={}
wrowi_bytime={}
wrowi_raw_bytime={}
wrowi_aec_bytime={}
for i in missing_bycountry.keys():
if missing_bycountry[i]1):
ax.text(WLD[frame+years[0]][0],WLD[frame+years[0]][1]-0.13,'World',horizontalalignment='center',size=13)
ax.plot([-100000,100000],[0, 0],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,zorder=0)
else:
ax.text(WLD[frame+years[0]][0],WLD[frame+years[0]][1]-0.35,'World',horizontalalignment='center',size=13)
ax.plot([-100000,100000],[1, 1],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,zorder=0)
#countries
#sort R list first, based on bubblesizes to arrange them in the z-plane and make sure smaller bubbles are on top
R[frame+years[0]]=np.array(sorted(np.array(R[frame+years[0]],dtype='object').T.tolist(),\
key=itemgetter(2),reverse=True),dtype='object').T.tolist()
x = R[frame+years[0]][0]
y = R[frame+years[0]][1]
sc=ax.scatter(x, y, np.array(R[frame+years[0]][2])*5,R[frame+years[0]][4],alpha=0.5,\
cmap = plt.cm.rainbow,vmin=-45,vmax=60,edgecolors=bgcolor(themeid))
ax.text(0.98,0.9,frame+years[0],size=30,\
horizontalalignment='right',transform=ax.transAxes)
for i, txt in enumerate(R[frame+years[0]][2]):
if R[frame+years[0]][2][i]>50:
#coose color, make darker or lighter, based on theme
if (themeid==0): col=np.array(cm.jet((R[frame+years[0]][4][i]+45)/105))*0.6
else: col=np.array(cm.jet((R[frame+years[0]][4][i]+45)/105))*0.9
col[3]=1 #set alpha back to 1
if (R[frame+years[0]][1][i] < ax.get_ylim()[1]): #put text only when fits into plot area
if (R[frame+years[0]][0][i] < ax.get_xlim()[1]): #put text only when fits into plot area
try: ax.text(R[frame+years[0]][0][i],R[frame+years[0]][1][i]-0.02,\
cc[country_name_converter4(R[frame+years[0]][3][i])][0],horizontalalignment='center',\
verticalalignment='center',size=7+R[frame+years[0]][2][i]**0.35,color=col)
except:
#put on USSR when it exists
if R[frame+years[0]][3][i]=='USSR':
ax.text(R[frame+years[0]][0][i],R[frame+years[0]][1][i]-0.02,\
'USSR',horizontalalignment='center',verticalalignment='center',size=7+R[frame+years[0]][2][i]**0.35,color=col)
#bubblesize
if logmode==0:
b_dist=[0.22,0.47,0.645]
if (wgtid==0): b_y=49800
elif (wgtid==1): b_y=8
else: b_y=30
b_base=0
elif logmode==1:
b_dist=[0.22,0.47,0.645]
if (wgtid==0): b_y=4.985
elif (wgtid==1): b_y=2
else: b_y=2
b_base=0
elif logmode==3:
b_dist=[0.087,0.187,0.257]
if (wgtid==0): b_y=4.985
elif (wgtid==1): b_y=2
else: b_y=30
b_base=1
else:
b_dist=[0.087,0.187,0.257]
if (wgtid==0): b_y=4.985
elif (wgtid==1): b_y=2
else: b_y=2
b_base=1
ax.scatter([b_y],[b_dist[0]-b_base],[1000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.scatter([b_y],[b_dist[1]-b_base],[5000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.scatter([b_y],[b_dist[2]-b_base],[10000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.text(b_y,2.3*b_dist[0]-b_base,'200',size=10, horizontalalignment='right',verticalalignment='center')
ax.text(b_y,2.3*b_dist[1]-b_base,'1000',size=10, horizontalalignment='right',verticalalignment='center')
ax.text(b_y,2.2*b_dist[2]-b_base,'2000',size=10, horizontalalignment='right',verticalalignment='center')
#colorbar
cbar=fig.colorbar(sc, cax=cax,extend='max')
cbar.set_label('Geographic latitude [degrees]',size=13)
cbar.set_alpha(1)
cbar.draw_all()
#regression - weighted after food energy output
#resort R list, based on GDP to facilitate regression plot
R[frame+years[0]]=np.array(sorted(np.array(R[frame+years[0]],dtype='object').T.tolist(),\
key=itemgetter(0)),dtype='object').T.tolist()
x = R[frame+years[0]][0]
y = R[frame+years[0]][1]
g = R[frame+years[0]][2] #weights for y
#comment out below to remove regression lines
try: # main line
x0=[-100000,100000]
#w = np.polynomial.polynomial.polyfit(x,y,1,w=1+np.log10(g)) #log weight
w = np.polynomial.polynomial.polyfit(x,y,1,w=g) #linear weight
#comment out next line to remove regression line
ax.plot([-3,-2],[0,0],color=textcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,\
zorder=0,label='energy output-weighted linear regression')
ax.plot(x0,w[1]*np.array(x0)+w[0],color=textcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
if False: #turn 80|20 regression on|off
ax.plot([-3,-2],[0,0],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,\
zorder=0,label='bottom 80% | top 20% regression')
try: #0-80
x1=x[0:int(len(x)*perc)]
x0=[x1[0],x1[len(x1)-1]]
y1=y[0:int(len(x)*perc)]
g1=g[0:int(len(x)*perc)]
w = np.polynomial.polynomial.polyfit(x1,y1,1,w=g1)
#comment out next line to remove regression line\n",
ax.plot(x0,w[1]*np.array(x0)+w[0],color=bgcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
try: #80-100
x2=x[int(len(x)*perc):len(x)]
x0=[x2[0],x2[len(x2)-1]]
y2=y[int(len(x)*perc):len(x)]
g2=g[int(len(x)*perc):len(x)]
w = np.polynomial.polynomial.polyfit(x2,y2,1,w=g2)
#comment out next line to remove regression line\n",
ax.plot(x0,w[1]*np.array(x0)+w[0],color=bgcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
ax.legend(loc=3,framealpha=0,fontsize=10)
fig.savefig(plotpath+repr(frame+years[0])+'_log'+repr(logmode)+'_'+title3[wgtid]+'roei'+repr(rawid)+repr(eroeiid)+repr(themeid)+'.png',bbox_inches = 'tight', \
pad_inches = 0.1, dpi=150, facecolor=bgcolor(themeid),edgecolor=bordercolor(themeid))
# In[177]:
perc=0.8 #income percentage - regression separator
eroeiid=0 #0 - food system, 1 - agri-system
rawid=0 #0 - adjusted eroei, 1 - raw eroei
wgtid=2 #0 - gdp, 1 - yld, 2 - eyld
logmode=0 #linear [0], loglin [1] or loglog [2] plot or linlog [3]
animvalues(eroeiid,rawid,wgtid)
#no JSAnimation version
themeid=1 #define theme id [currently 0 light 1 dark]
initplotcolors(themeid)
fig, ax = plt.subplots(1,1,subplot_kw=dict(axisbelow=True),figsize=(10,7.1))
cax = fig.add_axes([0.93, 0.13, 0.013, 0.78])
animate(50,themeid,eroeiid,rawid,wgtid) #plot world with theme themeid
# In[184]:
for wgtid in range(3): #define data source
for themeid in [1]: #define theme id [currently 0 light 1 dark]
initplotcolors(themeid)
for rawid in [0]: #0 - adjusted eroei, 1 - raw eroei
for eroeiid in [1]: #0 - food system, 1 - agri-system
for logmode in [1,2,3]: #linear [0], loglin [1] or loglog [2] plot
animvalues(eroeiid,rawid,wgtid)
for year in range(len(years)):
try:
fig, ax = plt.subplots(1,1,subplot_kw=dict(axisbelow=True),figsize=(10,7.1))
cax = fig.add_axes([0.93, 0.13, 0.013, 0.78])
animate(year,themeid,eroeiid,rawid,wgtid) #plot world with theme themeid
plt.close();
except: pass
# In[178]:
def animate2(frame, themeid, eroeiid, rawid, wgtid):
global ax,cax
#init axes
ax.cla()
cax.cla()
ax.tick_params(direction='out', pad=5)
ax.grid(color=bgcolor(themeid), linestyle='solid')
if (rawid==0): title='Food '
else: title='Agri-'
if (eroeiid==1): title2='(unadjusted)'
else: title2='(adjusted for crop energy content)'
if logmode==2:
ax.set_xlim(2,5)
ax.set_ylim(-1,1)
xlabels=[100,200,300,400,500,600,700,800,900,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,\
20000,30000,40000,50000,60000,70000,80000,90000,100000]
ax.set_xticks(np.log10(xlabels))
ax.set_xticklabels([100,'','','','','','','','',1000,'','','','','','','','',10000,'','','','','','','','',100000])
if (eroeiid==1):
if (rawid==1):
ax.set_xticklabels(['','','','','','','','','',1000,'','','','','','','','',10000,'','','','','','','','',100000])
ylabels=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10]
ax.set_yticks(np.log10(ylabels))
ax.set_yticklabels([0.1,0.2,'','',0.5,'','','','',1,2,'','',5,'','','','',10])
elif logmode==1:
ax.set_xlim(2,5)
ax.set_ylim(0,5)
xlabels=[100,200,300,400,500,600,700,800,900,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,\
20000,30000,40000,50000,60000,70000,80000,90000,100000]
ax.set_xticks(np.log10(xlabels))
ax.set_xticklabels([100,'','','','','','','','',1000,'','','','','','','','',10000,'','','','','','','','',100000])
if (eroeiid==1):
if (rawid==1):
ax.set_xticklabels(['','','','','','','','','',1000,'','','','','','','','',10000,'','','','','','','','',100000])
else:
ax.set_xlim(0,50000)
ax.set_ylim(0,5)
#world + line at EROEI=1
ax.plot(WLD[frame+years[0]][0], WLD[frame+years[0]][1],marker='^',lw=4,alpha=0.7,color="yellow",markersize=30)
if (logmode==2):
ax.text(WLD[frame+years[0]][0],WLD[frame+years[0]][1]-0.25,'World',horizontalalignment='center',size=13)
ax.plot([0,100000],[0, 0],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,zorder=0)
else:
ax.text(WLD[frame+years[0]][0],WLD[frame+years[0]][1]-0.65,'World',horizontalalignment='center',size=13)
ax.plot([0,100000],[1, 1],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,zorder=0)
#countries
#sort R list first, based on bubblesizes to arrange them in the z-plane and make sure smaller bubbles are on top
R[frame+years[0]]=np.array(sorted(np.array(R[frame+years[0]],dtype='object').T.tolist(),\
key=itemgetter(2),reverse=True),dtype='object').T.tolist()
x = R[frame+years[0]][0]
y = R[frame+years[0]][1]
sc=ax.scatter(x, y, np.array(R[frame+years[0]][2])*5,R[frame+years[0]][4],alpha=0.5,\
cmap = plt.cm.rainbow,vmin=-45,vmax=60,edgecolors=bgcolor(themeid))
for i, txt in enumerate(R[frame+years[0]][2]):
if R[frame+years[0]][2][i]>50:
#coose color, make darker or lighter, based on theme
if (themeid==0): col=np.array(cm.jet((R[frame+years[0]][4][i]+45)/105))*0.6
else: col=np.array(cm.jet((R[frame+years[0]][4][i]+45)/105))*0.9
col[3]=1 #set alpha back to 1
if (R[frame+years[0]][1][i] < ax.get_ylim()[1]): #put text only when fits into plot area
try: ax.text(R[frame+years[0]][0][i],R[frame+years[0]][1][i]-0.02,\
cc[country_name_converter4(R[frame+years[0]][3][i])][0],horizontalalignment='center',\
verticalalignment='center',size=7+R[frame+years[0]][2][i]**0.35,color=col)
except:
#put on USSR when it exists
if R[frame+years[0]][3][i]=='USSR':
ax.text(R[frame+years[0]][0][i],R[frame+years[0]][1][i]-0.02,\
'USSR',horizontalalignment='center',verticalalignment='center',size=7+R[frame+years[0]][2][i]**0.35,color=col)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
if (eroeiid==1):
ax.xaxis.set_ticks_position('bottom')
if (rawid==1):
ax.text(0.99,-0.18,'Bubble size: system energy output [TWh]',size=12, horizontalalignment='right',transform=ax.transAxes)
#bubblesize
if logmode==0:
b_dist=[0.42,0.9,1.22]
b_y=49800
b_base=0
elif logmode==1:
b_dist=[0.42,0.9,1.22]
b_y=4.985
b_base=0
else:
b_dist=[0.17,0.36,0.495]
b_y=4.985
b_base=1
ax.scatter([b_y],[b_dist[0]-b_base],[1000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.scatter([b_y],[b_dist[1]-b_base],[5000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.scatter([b_y],[b_dist[2]-b_base],[10000],facecolors='none',alpha=0.5,edgecolors=textcolor(themeid))
ax.text(b_y,2.3*b_dist[0]-b_base,'200',size=10, horizontalalignment='right',verticalalignment='center')
ax.text(b_y,2.3*b_dist[1]-b_base,'1000',size=10, horizontalalignment='right',verticalalignment='center')
ax.text(b_y,2.2*b_dist[2]-b_base,'2000',size=10, horizontalalignment='right',verticalalignment='center')
#colorbar
cbar=fig.colorbar(sc, cax=cax,extend='max')
cbar.set_label('Geographic latitude [degrees]',size=12)
cbar.set_alpha(1)
cbar.draw_all()
else:
ax.text(0.01,-0.18,'GDP / capita [current US$]',size=12, horizontalalignment='left',transform=ax.transAxes)
else:
ax.set_xticklabels([])
ax.set_title(title+'system',size=13,y=1.02)
if (rawid==1):
ax.set_yticklabels([])
if (eroeiid==0):
ax.text(0.97,0.97,frame+years[0],size=30,\
horizontalalignment='right',verticalalignment='top',transform=ax.transAxes)
else:
ax.yaxis.set_ticks_position('left')
ax.set_ylabel('EROEI '+title2,size=12)
#regression - weighted after food energy output
#resort R list, based on GDP to facilitate regression plot
R[frame+years[0]]=np.array(sorted(np.array(R[frame+years[0]],dtype='object').T.tolist(),\
key=itemgetter(0)),dtype='object').T.tolist()
x = R[frame+years[0]][0]
y = R[frame+years[0]][1]
g = R[frame+years[0]][2] #weights for y
#comment out below to remove regression lines
if logmode!=0: #regression does not make sense in pure linear scales plot
try: # main line
x0=[0,100000]
#w = np.polynomial.polynomial.polyfit(x,y,1,w=1+np.log10(g)) #log weight
w = np.polynomial.polynomial.polyfit(x,y,1,w=g) #linear weight
#comment out next line to remove regression line
ax.plot([-3,-2],[0,0],color=textcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,\
zorder=0,label='energy output-weighted linear regression')
ax.plot(x0,w[1]*np.array(x0)+w[0],color=textcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
if False: #turn 80|20 regression on|off
ax.plot([-3,-2],[0,0],color=bgcolor(themeid),linestyle='-',linewidth=2,alpha=0.8,\
zorder=0,label='bottom 80% | top 20% regression')
try: #0-80
x1=x[0:int(len(x)*perc)]
x0=[x1[0],x1[len(x1)-1]]
y1=y[0:int(len(x)*perc)]
g1=g[0:int(len(x)*perc)]
w = np.polynomial.polynomial.polyfit(x1,y1,1,w=g1)
#comment out next line to remove regression line\n",
ax.plot(x0,w[1]*np.array(x0)+w[0],color=bgcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
try: #80-100
x2=x[int(len(x)*perc):len(x)]
x0=[x2[0],x2[len(x2)-1]]
y2=y[int(len(x)*perc):len(x)]
g2=g[int(len(x)*perc):len(x)]
w = np.polynomial.polynomial.polyfit(x2,y2,1,w=g2)
#comment out next line to remove regression line\n",
ax.plot(x0,w[1]*np.array(x0)+w[0],color=bgcolor(themeid),linestyle='--',linewidth=2,alpha=0.8,zorder=0)
except: pass
if (eroeiid==1):
if (rawid==0):
ax.legend(loc=3,framealpha=0,fontsize=10)
plt.suptitle('Evolution of system EROEI vs. per capita GDP for all countries',size=17,y=0.98)
fig.savefig(plotpath+repr(frame+years[0])+'_log'+repr(logmode)+'_'+title3[wgtid]+'roei'+repr(themeid)+'.png',bbox_inches = 'tight', \
pad_inches = 0.1, dpi=150, facecolor=bgcolor(themeid),edgecolor=bordercolor(themeid))
# In[183]:
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(11,7.6))
gs = gridspec.GridSpec(2, 2)
gs.update(wspace=0.05, hspace=0.05)
axes=[]
for i in range(2):
axes.append([])
for j in range(2):
axes[i].append(plt.subplot(gs[i*2+j],axisbelow=True))
cax = fig.add_axes([0.93, 0.13, 0.013, 0.78])
logmode=3 #linear [0], loglin [1] or loglog [2] plot
wgtid=2
for eroeiid in range(2):
for rawid in range(2):
animvalues(rawid,eroeiid,wgtid)
ax=axes[eroeiid][rawid]
animate2(50,themeid,eroeiid,rawid,wgtid) #plot world with theme themeid
# In[ ]:
for wgtid in range(3): #define data source
for themeid in [0,1]: #define theme id [currently 0 light 1 dark]
initplotcolors(themeid)
for logmode in [0,1,2]: #linear [0], loglin [1] or loglog [2] plot
for year in range(len(years)):
try:
fig = plt.figure(figsize=(11,7.6))
gs = gridspec.GridSpec(2, 2)
gs.update(wspace=0.05, hspace=0.05)
axes=[]
for i in range(2):
axes.append([])
for j in range(2):
axes[i].append(plt.subplot(gs[i*2+j],axisbelow=True))
cax = fig.add_axes([0.93, 0.13, 0.013, 0.78])
for eroeiid in range(2):
for rawid in range(2):
animvalues(rawid,eroeiid,wgtid) #flipped intentionally
ax=axes[eroeiid][rawid]
animate2(0,themeid,eroeiid,rawid,wgtid) #plot world with theme themeid
plt.close();
except: pass
# EROEI is still heteroskedastic
# In[244]:
def eroeiplotter(themeid):
global ax
ax[0].grid(color=bgcolor(themeid), linestyle='solid')
ax[1].grid(color=bgcolor(themeid), linestyle='solid')
#food system- output energy weighted average
animvalues(0,0,0)
x=years
y=np.array([np.mean(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
s=np.array([np.std(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
line1 = ax[0].plot(x,y,linewidth=4,label="# World (calculated)",color="#22aa22")
line2 = ax[0].plot(x,eroei_bycountry['World + (Total)'][1],linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
ax[0].plot(x,[1 for i in range(len(x))],linestyle="-",linewidth=2,color=bgcolor(themeid),zorder=0)
ax[0].plot(0,0,linewidth=8,c=u'#22aa22',label='$\sigma$',alpha=0.3)
fill=ax[0].fill_between(x, y+s, y-s, facecolor=u'#22aa22', alpha=0.3)
#agri-system - output energy weighted average
animvalues(1,0,0)
y=np.array([np.mean(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
s=np.array([np.std(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
line1 = ax[1].plot(x,y,linewidth=4,label="# World (calculated)",color="#22aa22")
line2 = ax[1].plot(x,eroei_bycountry2['World + (Total)'][1],linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
ax[1].plot(x,[1 for i in range(len(x))],linestyle="-",linewidth=2,color=bgcolor(themeid),zorder=0)
ax[1].plot(0,0,linewidth=8,c=u'#22aa22',label='$\sigma$',alpha=0.3)
fill=ax[1].fill_between(x, y+s, y-s, facecolor=u'#22aa22', alpha=0.3)
for i in range(2):
ax[i].set_xlim([1960,2011])
ax[i].set_ylim([0,10])
ax[i].set_xlabel('Year',labelpad=5, size=12)
ax[i].legend(framealpha=0.5,loc=2,fontsize=10)
ax[0].set_ylabel('Food system EROEI',labelpad=10, size=12)
ax[1].set_ylabel('Agri-system EROEI',labelpad=10, size=12)
plt.suptitle("Energy return on energy invested (EROEI)", size=16, y=1.02)
plt.savefig(plotpath+'EROEI'+repr(themeid)+'.png',bbox_inches = 'tight', pad_inches = 0.1, dpi=150,
facecolor=bgcolor(themeid),edgecolor=bordercolor(themeid))
# In[245]:
#define list flattener #http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
flatten = lambda *n: (e for a in n
for e in (flatten(*a) if isinstance(a, (tuple, list)) else (a,)))
def eroeiplotter2(themeid):
global ax
label=['Food ','Agri-']
rlabel=['(adjusted for crop energy content)','(unadjusted)']
for k in range(2):
for i in range(2):
#system output energy weighted average
animvalues(i,k,0) #eroeiid (0-food, 1-agri), rawid
y=np.array([np.mean(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
s=np.array([np.std(np.array([R[year][1][j]*R[year][2][j]/np.mean(R[year][2]) for j in range(len(R[year][1]))])) for year in years])
ax[k][i*2].grid(color=bgcolor(themeid), linestyle='solid')
ax[k][i*2+1].grid(color=bgcolor(themeid), linestyle='solid')
ax[k][i*2].plot(years,y,linewidth=4,label="# World (calculated)",color="#22aa22")
if (i==0):
if (k==0):ax[k][i*2].plot(years,[eroei_bycountry['World + (Total)'][1][year] for year in range(len(years))],\
linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
else: ax[k][i*2].plot(years,[eroei_raw_bycountry['World + (Total)'][1][year] for year in range(len(years))],\
linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
else:
if (i==0):ax[k][i*2].plot(years,[eroei_bycountry2['World + (Total)'][1][year] for year in range(len(years))],\
linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
else: ax[k][i*2].plot(years,[eroei_raw_bycountry2['World + (Total)'][1][year] for year in range(len(years))],\
linewidth=4,color="#ff6600",label="~ World (FAO aggregate)")
ax[k][i*2].plot(years,[1 for j in range(len(years))],linestyle="-",linewidth=2,color=bgcolor(themeid),zorder=0)
ax[k][i*2].plot(0,0,linewidth=8,c=u'#22aa22',label='$\sigma$',alpha=0.3)
fill=ax[k][i*2].fill_between(years, y+s, y-s, facecolor=u'#22aa22', alpha=0.3)
ax[k][i*2+1].hist(list(flatten([[R[year][1][j]*R[year][2][j] for j in range(len(R[year][1]))] for year in years])),\
bins=np.arange(20)/2.0,orientation="horizontal",color="#22aa22",alpha=0.3)
ax[k][i*2].set_xlim([1960,2011])
ax[k][i*2].set_ylim([0,10])
ax[k][i*2].legend(framealpha=0.5,loc=2,fontsize=10)
ax[k][i*2+1].set_yticklabels([])
ax[k][i*2+1].set_xticks([])
if (i==1):
ax[k][i*2+1].set_yticklabels([])
ax[k][i*2].set_yticklabels([])
else:
ax[k][i*2].set_ylabel('EROEI '+rlabel[k],labelpad=5, size=12)
if (k==0):
ax[k][i*2].set_xticklabels([])
ax[k][i*2].set_title(label[i]+'system',y=1.02,size=12)
else:
ax[k][i*2].set_xlabel('Year',labelpad=5, size=12)
ax[0][2].text(-0.05,1.15,"Evolution of global energy return on energy invested (EROEI)\nof food and agriculture systems weighted by energy output",\
size=16,horizontalalignment='center',verticalalignment='bottom',transform=ax[0][2].transAxes)
plt.savefig(plotpath+'EROEI_hist'+repr(themeid)+'.png',bbox_inches = 'tight', pad_inches = 0.1, dpi=150,
facecolor=bgcolor(themeid),edgecolor=bordercolor(themeid))
# In[ ]:
logmode=0
initplotcolors(themeid)
fig, ax = plt.subplots(1,2,subplot_kw=dict(axisbelow=True),figsize=(11,4))
eroeiplotter(themeid)
fig = plt.figure(figsize=(18.5,7))
gs = gridspec.GridSpec(2, 5,width_ratios=[20,6,0.3,20,6,20,6,0.3,20,6])
gs.update(left=0.05, right=0.98, wspace=0.05, hspace=0.05)
ax=[]
for i in range(2):
ax.append([])
for j in range(5):
if (j!=2):
ax[i].append(plt.subplot(gs[i*5+j],axisbelow=True))
eroeiplotter2(themeid)
# In[ ]:
logmode=0
for themeid in [0,1]:
initplotcolors(themeid)
fig, ax = plt.subplots(1,2,subplot_kw=dict(axisbelow=True),figsize=(13,4))
eroeiplotter(themeid)
plt.close()
fig = plt.figure(figsize=(18.5,7))
gs = gridspec.GridSpec(2, 5,width_ratios=[20,6,0.3,20,6,20,6,0.3,20,6])
gs.update(left=0.05, right=0.98, wspace=0.05, hspace=0.05)
ax=[]
for i in range(2):
ax.append([])
for j in range(5):
if (j!=2):
ax[i].append(plt.subplot(gs[i*5+j],axisbelow=True))
eroeiplotter2(themeid)
plt.close()
# HMTL side-by-side plot
# In[251]:
logmode=2 #loglog
animvalues(0,0)
fig,ax = plt.subplots(1,subplot_kw=dict(axisbg='#EEEEEE'))
ax.grid(color='white', linestyle='solid')
ax2=ax.twinx();
#ax2.grid(color='white', linestyle='solid')
ax.plot(p.keys(),p.values(),linewidth=2,color='b')
ax2.plot(p.keys(),g,linewidth=2,color='r')
ax.set_title("EROEI = f(GDP) regression slope parameter m", y=1.05, size=14)
ax.set_xlabel('Years',labelpad=10)
ax.set_ylabel('m (all countries included)',color='b')
ax2.set_ylabel('GDP / capita [2005 constant $]',labelpad=10,color='r')
ax.set_xlim([1960,2011])
fig.savefig(plotpath+'gdp_eroei.png',bbox_inches = 'tight', pad_inches = 0.1, dpi=150)
plt.show()
# # Mapping yeah
# In[186]:
#load empty data.csv
foodmap=pd.read_csv(masterpath.replace('db','map/0')+'data_empty.csv')
#convert years from 1999.0 format to 1999 for csv, quite trciky with pandas
foodmap["YEAR"]=foodmap["YEAR"].fillna("").astype(str)
for i in foodmap.index:
foodmap.loc[i,"YEAR"]=foodmap.loc[i,"YEAR"][0:4]
# fill foodmap dataframe
# In[187]:
for c in eroei_bycountry.keys():
try:
for i in range(len(eroei_bycountry[c][0])):
foodmap.loc[(2011-int(eroei_bycountry[c][0][i]))*6+1,cc[country_name_converter4(c)][0]]=\
eroei_bycountry[c][1][i]
foodmap.loc[(2011-int(eroei_bycountry2[c][0][i]))*6+2,cc[country_name_converter4(c)][0]]=\
eroei_bycountry2[c][1][i]
foodmap.loc[(2011-int(fooden_bycountry2[c][0][i]))*6+3,cc[country_name_converter4(c)][0]]=\
fooden_bycountry2[c][1][i]
except: pass
for i in gdp.index:
try:
for j in gdp.loc[i].iteritems():
foodmap.loc[(2011-j[0])*6+4,cc[country_name_converter4(i)][0]]=j[1]
except: pass
# save files for statplanet
# In[189]:
foodmap.to_csv(masterpath.replace('db','map/0')+'data.csv',index=False)
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
zf = zipfile.ZipFile(masterpath.replace('db','map/0')+'data.zip', mode='w')
zf.write(masterpath.replace('db','map/0')+'data.csv','data.csv',compress_type=compression)
zf.close()
#
We would like to express our gratitude to all of the developers of the libraries used and especially to the affiliates of *FAOSTAT* for their great database and openly accesible data. The data manipulation algorithms and visualization techniques are open sourced and freely reproducible, forks are welcome on GitHub. The concept and methodology are subject to copyright of the authors.
# © 2020
# http://food.csaladen.es