Skip to content

Commit

Permalink
plus_minus graphs
Browse files Browse the repository at this point in the history
  • Loading branch information
Sven Eggimann committed Apr 18, 2019
1 parent f4597ea commit 74791de
Show file tree
Hide file tree
Showing 3 changed files with 205 additions and 44 deletions.
67 changes: 67 additions & 0 deletions energy_demand/plotting/_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Dataset
ax = plt.subplot(111)

dataright = np.random.rand(10, 4)
dataleft = dataright * -1
df_right = pd.DataFrame(dataright, columns=['a', 'b', 'c', 'd'])
df_left = pd.DataFrame(dataleft, columns=['a', 'b', 'c', 'd'])


# plot WORKDS
#labels_minus = list(df_left.values)
#labels_plus = list(df_right.values)
#labels = labels_minus + labels_plus

'''
df_right.plot(kind='barh', stacked=True, width=1.0)
df_left.plot(kind='barh',stacked=True, width=1.0)'''


fig, ax = plt.subplots(ncols=1, sharey=True)

##ax.invert_xaxis()
##ax.yaxis.tick_right()
#ax.set_yticklabels(labels)
# Add vertical line
ax.axvline(linewidth=1, color='black')

df_right.plot(kind='barh', legend=True, ax=ax, width=1.0, stacked=True)
df_left.plot(kind='barh', legend=True, ax=ax, width=1.0, stacked=True)
plt.show()

#raise Exception

#https://stackoverflow.com/questions/44049132/python-pandas-plotting-two-barh-side-by-side
#df = pd.DataFrame()

#df_1[target_cols].plot(kind='barh', x='LABEL', stacked=True, legend=False)
#df_2[target_cols].plot(kind='barh', x='LABEL', stacked=True).invert_xaxis()

#x_axis = [list(df_right.index)]
#print(x_axis)
#print("...")
#print(np.array([5., 30., 45., 22.]))
##plt.barh(np.arange(4), np.array([5., 30., 45., 22.]), color = 'r')
#plt.barh(x_axis, df_right, color = 'r', stacked='True')
#plt.barh(x_axis, df_right, color='r', stacked=True)
#plt.barh(x_axis, df_left, color='b', stacked=True)

#plt.show()#
#print("..")

'''
import numpy as np
import matplotlib.pyplot as plt
women_pop = np.array([5., 30., 45., 22.])
men_pop = np.array( [5., 25., 50., 20.])
X = np.arange(4)
plt.barh(X, women_pop, color = 'r')
plt.barh(X, -men_pop, color = 'b')
plt.show()
'''
27 changes: 20 additions & 7 deletions energy_demand/plotting/chaudry_et_al.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,28 @@
...
'''
import os
import shutil
from energy_demand.plotting import chaudry_et_al_functions #Reset imports


# -----------------------------------
# Configure paths
# -----------------------------------
path_out = "C:/_test" # Path to store results

path_in = "C:/Users/cenv0553/nismod2/results/PLOTTINGFOLDER" # Path with results

scenarios = ['EV'] #'MV',
# Configure simulation names
simulation_name = 'energy_sd_constrained' # Name of model

scenarios = ['EW'] #'MV',
weather_scenario = 'NF1'
fueltype = 'electricity'


# ------------------------
# Create empty result folders
# Create empty result folders and delte preivous results
# ------------------------
shutil.rmtree(path_out) # delete results
chaudry_et_al_functions.create_folder(path_out)

paths_figs = ['fig3', 'fig4', 'fig5', 'fig6']
Expand All @@ -47,15 +52,23 @@
# ------------------------
data_container = chaudry_et_al_functions.load_data(
path_in,
simulation_name=simulation_name,
scenarios=scenarios)

print("loaded data")

# ------------------------
# Create figures
# ------------------------
chaudry_et_al_functions.fig_3(data_container, fueltype=fueltype)
chaudry_et_al_functions.fig_4(data_container, fueltype=fueltype)
chaudry_et_al_functions.fig_5(data_container, fueltype=fueltype)
chaudry_et_al_functions.fig_6(data_container, fueltype=fueltype)
# Figure with vertical hourly values per scenario
chaudry_et_al_functions.fig_3(
path_out,
data_container,
scenarios=scenarios,
weather_scearnio=weather_scenario,
fueltype=fueltype)

#chaudry_et_al_functions.fig_4(data_container, fueltype=fueltype)
#chaudry_et_al_functions.fig_5(data_container, fueltype=fueltype)
#chaudry_et_al_functions.fig_6(data_container, fueltype=fueltype)
print("Finished creasting figures")
155 changes: 118 additions & 37 deletions energy_demand/plotting/chaudry_et_al_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ def create_folder(path_folder, name_subfolder=None):
if not os.path.exists(path_result_subolder):
os.makedirs(path_result_subolder)

def load_data(in_path, scenarios):
def load_data(in_path, scenarios, simulation_name):
"""Read results
Returns
data_container : [scenario][mode][weather_scenario
"""

data_container = {}
Expand All @@ -36,7 +39,7 @@ def load_data(in_path, scenarios):
data_container[scenario][mode] = {}

# Iterate over weather scenarios
path_scenarios = os.path.join(in_path, scenario, mode, 'energy_supply_constrained', 'decision_0')
path_scenarios = os.path.join(in_path, scenario, mode)
weather_scenarios = os.listdir(path_scenarios)

for weather_scenario in weather_scenarios:
Expand All @@ -45,8 +48,8 @@ def load_data(in_path, scenarios):
# ---------------------------
# Load supply generation mix
# ---------------------------
data_container[scenario][mode]['energy_supply_constrained'] = {}
path_supply_mix = os.path.join(in_path, scenario, mode, weather_scenario, 'energy_supply_constrained', 'decision_0')
data_container[scenario][mode][weather_scenario] ['energy_supply_constrained'] = {}
path_supply_mix = os.path.join(in_path, scenario, mode, weather_scenario, simulation_name, 'energy_supply_constrained', 'decision_0')

all_files = os.listdir(path_supply_mix)

Expand All @@ -57,50 +60,128 @@ def load_data(in_path, scenarios):
# Load data
data_file = pd.read_csv(path_file)

# Set energy_hub as index
try:
# Aggregate across every energy hub region and group by "seasonal week"
df_to_plot_national = data_file.groupby(data_file['seasonal_week']).sum()

# Set seasonal week attribute as index
df_to_plot_national.set_index('seasonal_week')
except:
print("{} has wrong format".format(file_name))
'''# Set energy_hub as index
try:
data_file.set_index('energy_hub')
except:
print("... file does not have 'energy_hub' as column")
print("... file does not have 'energy_hub' as column")'''

data_container[scenario][mode][weather_scenario]['supply_mix'][file_name] = data_file
data_container[scenario][mode][weather_scenario]['energy_supply_constrained'][file_name] = df_to_plot_national

return data_container


def fig_3(data_container, fueltype='electricity'):
"""
def fig_3(path_out, data_container, scenarios, weather_scearnio, fueltype, years=[2015, 2030, 2050]):
"""Create x-y chart of a time-span (x-axis: demand, y-axis: time)
"""

# Create x-y chart of a time-span (x-axis: demand, y-axis: time)


# Dataset
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

# Invert axis (df1.T)
# plot
df.plot.area()

'''data = np.random.rand(10, 4)
columns = ['a', 'b', 'c', 'd']
df = pd.DataFrame(data, columns=columns)
df.plot.area()
df.plot.hist(stacked=True, orientation='horizontal')
#plt.show()
print("t")
ax = plt.gca()
ax.invert_xaxis()
#plt.gca().invert_yaxis()
#df = pd.DataFrame(data, columns=columns)
#df.plot.area()
plt.show()
print("t")
raise Exception
'''
technologies_to_plot = {
electricity': [
'output_industry_electricity_boiler_electricity_timestep',
'output_industry_electricity_district_heating_electricity_timestep',
'output_industry_electricity_heat_pumps_electricity_timestep',
'output_industry_electricity_non_heating_timestep_2015',
'output_service_electricity_boiler_electricity_timestep',
'output_service_electricity_district_heating_electricity_timestep',
'output_service_electricity_heat_pumps_electricity_timestep',
'output_service_electricity_non_heating_timestep',
'output_residential_electricity_boiler_electricity_timestep',
'output_residential_electricity_district_heating_electricity_timestep',
'output_residential_electricity_heat_pumps_electricity_timestep',
'output_residential_electricity_non_heating_timestep'
]
}
'''
file_names_to_plot = {
'electricity': [
'output_eh_electricboiler_b_timestep',
'output_eh_heatpump_b_timestep',
'output_eh_pv_power_timestep',
]}

fig_dict = {}
path_out_folder = os.path.join(path_out, 'fig3')

for year in years:
fig_dict[year] = {}
for mode in ['DECENTRAL', 'CENTRAL']:
fig_dict[year][mode] = {}

for scenario in scenarios:
fig_dict[year][mode][scenario] = {}

data_files = data_container[scenario][mode][weather_scearnio]['energy_supply_constrained']

files_to_plot = file_names_to_plot[fueltype]

# Get all correct data to plot
df_to_plot = pd.DataFrame()

for file_name, file_data in data_files.items():

file_name_split_without_timpestep = file_name[:-9] #remove ending

file_name_split = file_name.split("_")
year_simulation = int(file_name_split[-1][:4])

if (year == year_simulation) and (file_name_split_without_timpestep in files_to_plot):
value_column = list(file_data.columns)[1]
print("File_name: {} Value column: {}".format(file_name_split_without_timpestep, value_column))
df_to_plot[str(value_column)] = file_data[value_column]

# Aggregate across every energy hub region and group by "seasonal week"
#df_to_plot_national = df_to_plot.groupby(df_to_plot['seasonal_week']).sum()

# Select hours to plots
hours_selected = range(1, 25) #TODO SELECT TIME INTERVALE TP LOT
df_to_plot_hrs_to_plot = df_to_plot.loc[hours_selected]

fig_dict[year][mode][scenario] = df_to_plot_hrs_to_plot

print("--ploting --") #MOVE DOWN ELEMENTS

# ----------
# Plot graph
# ----------
for scenario in scenarios:
df_right = fig_dict[year]['CENTRAL'][scenario]
df_left = fig_dict[year]['CENTRAL'][scenario] * -1 #Muptplied
#df_to_plot.plot.area()
#df_to_plot.plot.bar(stacked=True)#, orientation='vertical')

# Add vertical line
fig, ax = plt.subplots(ncols=1, sharey=True)
ax.axvline(linewidth=1, color='black')

df_right.plot(kind='barh', legend=True, ax=ax, width=1.0, stacked=True)
df_left.plot(kind='barh', legend=True, ax=ax, width=1.0, stacked=True)

#plt.show()

#ax = plt.gca()
#ax.invert_xaxis()

#plt.gca().invert_yaxis()
#df = pd.DataFrame(data, columns=columns)
#df.plot.area()
#plt.show()

# Save pdf
fig_name = "{}_{}".format(scenario, year)
path_out_file = os.path.join(path_out_folder, "{}.pdf".format(fig_name))
plt.savefig(path_out_file)
raise Exception("FF")
return


Expand Down

0 comments on commit 74791de

Please sign in to comment.