The following code runs perfectly and creates a dataframe
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import matplotlib as mpl
sns.set()
df = pd.DataFrame({
# some ways to create random data
'scenario':np.random.choice( ['BAU','ETS','ESD'], 27),
'region':np.random.choice( ['Italy','France'], 27),
'variable':np.random.choice( ['GDP','GHG'], 27),
# some ways to create systematic groups for indexing or groupby
# this is similar to r's expand.grid(), see note 2 below
'2015':np.random.randn(27),
'2016':np.random.randn(27),
'2017':np.random.randn(27),
'2018':np.random.randn(27),
'2019':np.random.randn(27),
'2020':np.random.randn(27),
'2021':np.random.randn(27)
})
df2=pd.melt(df,id_vars=['scenario','region','variable'],var_name='year')
all_names_index = df2.set_index(['scenario','region','variable','year']).sort_index()
Then I use a function to plot iteratively:
def name_plot(scenario, region, variable):
data = all_names_index.loc[scenario, region, variable]
plt.plot(data.index, data.value, label='%s' % scenario)
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 13}
plt.rc('font', **font)
names = ['BAU','ETS', 'ESD']
for scenario in names:
name_plot(scenario, 'Italy', 'GHG')
plt.xlabel('Years')
plt.ylabel('MtCO2e')
plt.title('Emissions Pathways')
plt.legend()
plt.savefig('EMIp.png')
plt.clf()
As I need to create a region EU as the sum of the othe two countries, I create a pivot_table:
map_eu = {
'EU' : ['Italy','France']
}
df3=pd.pivot_table(df2, 'value', ['scenario', 'variable', 'year'], 'region')
for k,v in map_eu.items():
df3[k] = df3[v].sum(1)
df3 = df3.stack(0).unstack(1)
df3.sort_index(0,inplace=True)
How can I plot df3 with the function name_plot defined before? I cannot understand how to re-arrange the pivot_table to obtain the same structure of df2