def plot_tot_fueltype_y_over_time(scenario_data,
                                  fueltypes,
                                  fueltypes_to_plot,
                                  fig_name,
                                  txt_name,
                                  plotshow=False):
    """Plot total demand over simulation period for every
    scenario for all regions
    """
    results_txt = []

    # Set figure size
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(9, 8))

    ax = fig.add_subplot(1, 1, 1)

    y_scenario = {}

    for scenario_name, scen_data in scenario_data.items():

        # Read out fueltype specific max h load
        data_years = {}
        for year, fueltype_reg_time in scen_data['ed_fueltype_regs_yh'].items(
        ):

            # Sum all regions
            tot_gwh_fueltype_yh = np.sum(fueltype_reg_time, axis=1)

            # Sum all hours
            tot_gwh_fueltype_y = np.sum(tot_gwh_fueltype_yh, axis=1)

            # Convert to TWh
            tot_gwh_fueltype_y = conversions.gwh_to_twh(tot_gwh_fueltype_y)

            data_years[year] = tot_gwh_fueltype_y

        y_scenario[scenario_name] = data_years

    # -----------------
    # Axis
    # -----------------
    base_yr, year_interval = 2020, 10
    first_scen = list(y_scenario.keys())[0]
    end_yr = list(y_scenario[first_scen].keys())

    major_ticks = np.arange(base_yr, end_yr[-1] + year_interval, year_interval)

    plt.xticks(major_ticks, major_ticks)

    # ----------
    # Plot lines
    # ----------
    #color_list_selection_fueltypes = plotting_styles.color_list_selection()
    color_list_selection = plotting_styles.color_list_scenarios()
    linestyles = ['--', '-', ':', "-.",
                  ".-"]  #linestyles = plotting_styles.linestyles()

    cnt_scenario = -1
    for scenario_name, fuel_fueltype_yrs in y_scenario.items():
        cnt_scenario += 1
        color = color_list_selection[cnt_scenario]
        cnt_linestyle = -1

        for fueltype_str, fueltype_nr in fueltypes.items():

            if fueltype_str in fueltypes_to_plot:
                cnt_linestyle += 1
                # Get fuel per fueltpye for every year
                fuel_fueltype = []
                for entry in list(fuel_fueltype_yrs.values()):
                    fuel_fueltype.append(entry[fueltype_nr])

                plt.plot(
                    list(fuel_fueltype_yrs.keys()),  # years
                    fuel_fueltype,  # yearly data per fueltype
                    color=color,
                    linestyle=linestyles[cnt_linestyle],
                    label="{}_{}".format(scenario_name, fueltype_str))

                # ---
                # Calculate difference in demand from 2015 - 2050
                # ---
                tot_2015 = fuel_fueltype[0]
                tot_2050 = fuel_fueltype[-1]
                diff_abs = tot_2050 - tot_2015
                p_diff_2015_2015 = ((100 / tot_2015) * tot_2050) - 100  # Diff

                txt = "fueltype_str: {} ed_tot_by: {} ed_tot_cy: {}, diff_p: {}, diff_abs: {} scenario: {}".format(
                    fueltype_str, round(tot_2015, 1), round(tot_2050, 1),
                    round(p_diff_2015_2015, 1), round(diff_abs, 1),
                    scenario_name)

                results_txt.append(txt)

    # --------------------------
    # Save model results to txt
    # --------------------------
    write_data.write_list_to_txt(txt_name, results_txt)

    # ----
    # Axis
    # ----
    plt.ylim(ymin=0)

    # ------------
    # Plot legend
    # ------------
    ax.legend(ncol=2,
              frameon=False,
              loc='upper center',
              prop={
                  'family': 'arial',
                  'size': 4
              },
              bbox_to_anchor=(0.5, -0.1))

    # ---------
    # Labels
    # ---------
    font_additional_info = plotting_styles.font_info(size=5)

    plt.ylabel("TWh")
    plt.xlabel("year")

    # Tight layout
    plt.tight_layout()
    plt.margins(x=0)

    plt.savefig(fig_name)

    if plotshow:
        plt.show()

    plt.close()
def plot_tot_y_over_time(scenario_data, fig_name, plotshow=False):
    """Plot total demand over simulation period for every
    scenario for all regions
    """
    # Set figure size
    plt.figure(figsize=basic_plot_functions.cm2inch(14, 8))

    y_scenario = {}

    for scenario_name, scen_data in scenario_data.items():

        # Read out fueltype specific max h load
        data_years = {}
        for year, fueltype_reg_time in scen_data['ed_fueltype_regs_yh'].items(
        ):

            # Sum all regions and fueltypes
            tot_gwh_fueltype_y = np.sum(fueltype_reg_time)

            # Convert to TWh
            tot_twh_fueltype_y = conversions.gwh_to_twh(tot_gwh_fueltype_y)

            data_years[year] = tot_twh_fueltype_y

        y_scenario[scenario_name] = data_years

    # -----------------
    # Axis
    # -----------------
    base_yr, year_interval = 2015, 5
    first_scen = list(y_scenario.keys())[0]
    end_yr = list(y_scenario[first_scen].keys())

    major_ticks = np.arange(base_yr, end_yr[-1] + year_interval, year_interval)

    plt.xticks(major_ticks, major_ticks)

    # ----------
    # Plot lines
    # ----------
    # color_list_selection = plotting_styles.color_list_selection()
    color_list_selection = plotting_styles.color_list_scenarios()

    for scenario_name, fuel_fueltype_yrs in y_scenario.items():

        plt.plot(
            list(fuel_fueltype_yrs.keys()),  # years
            list(fuel_fueltype_yrs.values()),  # yearly data per fueltype
            color=str(color_list_selection.pop()),
            label=scenario_name)

    # ----
    # Axis
    # ----
    plt.ylim(ymin=0)

    # ------------
    # Plot legend
    # ------------
    plt.legend(ncol=1,
               loc=3,
               prop={
                   'family': 'arial',
                   'size': 10
               },
               frameon=False)

    # ---------
    # Labels
    # ---------
    plt.ylabel("TWh")
    plt.xlabel("year")
    plt.title("tot y ED all fueltypes")

    # Tight layout
    plt.tight_layout()
    plt.margins(x=0)

    plt.savefig(fig_name)

    if plotshow:
        plt.show()

    plt.close()
Ejemplo n.º 3
0
def fueltypes_over_time(scenario_result_container,
                        sim_yrs,
                        fig_name,
                        fueltypes,
                        result_path,
                        plot_points=False,
                        unit='TWh',
                        crit_smooth_line=True,
                        seperate_legend=False):
    """Plot fueltypes over time
    """
    statistics_to_print = []

    fig = plt.figure(figsize=basic_plot_functions.cm2inch(10,
                                                          10))  #width, height
    ax = fig.add_subplot(1, 1, 1)

    colors = {
        # Low elec
        'electricity': '#3e3838',
        'gas': '#ae7c7c',
        'hydrogen': '#6cbbb3',
    }

    line_styles_default = plotting_styles.linestyles()

    linestyles = {
        'h_max': line_styles_default[0],
        'h_min': line_styles_default[6],
        'l_min': line_styles_default[8],
        'l_max': line_styles_default[9],
    }

    for cnt_scenario, i in enumerate(scenario_result_container):
        scenario_name = i['scenario_name']

        for cnt_linestyle, fueltype_str in enumerate(fueltypes):
            national_sum = i['national_{}'.format(fueltype_str)]

            if unit == 'TWh':
                unit_factor = conversions.gwh_to_twh(1)
            elif unit == 'GWh':
                unit_factor = 1
            else:
                raise Exception("Wrong unit")

            national_sum = national_sum * unit_factor

            # Calculate quantiles
            quantile_95 = 0.95
            quantile_05 = 0.05

            try:
                color = colors[fueltype_str]
            except KeyError:
                #color = list(colors.values())[cnt_linestyle]
                raise Exception("Wrong color")

            try:
                linestyle = linestyles[scenario_name]
            except KeyError:
                linestyle = list(linestyles.values())[cnt_scenario]
            try:
                marker = marker_styles[scenario_name]
            except KeyError:
                marker = list(marker_styles.values())[cnt_scenario]

            # Calculate average across all weather scenarios
            mean_national_sum = national_sum.mean(axis=0)
            mean_national_sum_sim_yrs = copy.copy(mean_national_sum)

            statistics_to_print.append(
                "{} fueltype_str: {} mean_national_sum_sim_yrs: {}".format(
                    scenario_name, fueltype_str, mean_national_sum_sim_yrs))

            # Standard deviation over all realisations
            df_q_05 = national_sum.quantile(quantile_05)
            df_q_95 = national_sum.quantile(quantile_95)

            statistics_to_print.append(
                "{} fueltype_str: {} df_q_05: {}".format(
                    scenario_name, fueltype_str, df_q_05))
            statistics_to_print.append(
                "{} fueltype_str: {} df_q_95: {}".format(
                    scenario_name, fueltype_str, df_q_95))
            # --------------------
            # Try to smooth lines
            # --------------------
            sim_yrs_smoothed = sim_yrs
            if crit_smooth_line:
                try:
                    sim_yrs_smoothed, mean_national_sum_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, mean_national_sum, num=500)
                    _, df_q_05_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, df_q_05, num=500)
                    _, df_q_95_smoothed = basic_plot_functions.smooth_data(
                        sim_yrs, df_q_95, num=500)

                    mean_national_sum = pd.Series(mean_national_sum_smoothed,
                                                  sim_yrs_smoothed)
                    df_q_05 = pd.Series(df_q_05_smoothed, sim_yrs_smoothed)
                    df_q_95 = pd.Series(df_q_95_smoothed, sim_yrs_smoothed)
                except:
                    print("did not owrk {} {}".format(fueltype_str,
                                                      scenario_name))
                    pass

            # ------------------------
            # Plot lines
            # ------------------------
            plt.plot(mean_national_sum,
                     label="{} {}".format(fueltype_str, scenario_name),
                     linestyle=linestyle,
                     color=color,
                     zorder=1,
                     clip_on=True)

            # ------------------------
            # Plot markers
            # ------------------------
            if plot_points:
                plt.scatter(sim_yrs,
                            mean_national_sum_sim_yrs,
                            marker=marker,
                            edgecolor='black',
                            linewidth=0.5,
                            c=color,
                            zorder=2,
                            s=15,
                            clip_on=False)  #do not clip points on axis

            # Plottin qunatilse and average scenario
            df_q_05.plot.line(color=color,
                              linestyle='--',
                              linewidth=0.1,
                              label='_nolegend_')  #, label="0.05")
            df_q_95.plot.line(color=color,
                              linestyle='--',
                              linewidth=0.1,
                              label='_nolegend_')  #, label="0.05")

            plt.fill_between(
                sim_yrs_smoothed,
                list(df_q_95),  #y1
                list(df_q_05),  #y2
                alpha=0.25,
                facecolor=color,
            )

    plt.xlim(2015, 2050)
    plt.ylim(0)

    ax = plt.gca()

    # Major ticks every 20, minor ticks every 5
    major_ticks = [200, 400, 600]  #np.arange(0, 600, 200)
    minor_ticks = [100, 200, 300, 400, 500, 600]  #np.arange(0, 600, 100)

    ax.set_yticks(major_ticks)
    ax.set_yticks(minor_ticks, minor=True)

    # And a corresponding grid
    ax.grid(which='both',
            color='black',
            linewidth=0.5,
            axis='y',
            linestyle=line_styles_default[3])  #[6])

    # Or if you want different settings for the grids:
    ax.grid(which='minor', axis='y', alpha=0.4)
    ax.grid(which='major', axis='y', alpha=0.8)

    # Achsen
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)

    # Ticks
    plt.tick_params(
        axis='y',  # changes apply to the x-axis
        which='both',  # both major and minor ticks are affected
        bottom=False,  # ticks along the bottom edge are off
        top=False,  # ticks along the top edge are off
        left=False,
        right=False,
        labelbottom=False,
        labeltop=False,
        labelleft=True,
        labelright=False)  # labels along the bottom edge are off

    # --------
    # Legend
    # --------
    legend = plt.legend(
        #title="tt",
        ncol=2,
        prop={'size': 6},
        loc='upper center',
        bbox_to_anchor=(0.5, -0.1),
        frameon=False)
    legend.get_title().set_fontsize(8)

    if seperate_legend:
        basic_plot_functions.export_legend(
            legend, os.path.join(result_path,
                                 "{}__legend.pdf".format(fig_name)))
        legend.remove()

    # --------
    # Labeling
    # --------
    plt.ylabel("national fuel over time [in {}]".format(unit))
    #plt.xlabel("year")
    #plt.title("Title")

    plt.tight_layout()
    #plt.show()
    plt.savefig(os.path.join(result_path, fig_name))
    plt.close()

    write_data.write_list_to_txt(
        os.path.join(result_path, fig_name).replace(".pdf", ".txt"),
        statistics_to_print)
Ejemplo n.º 4
0
def run(lookups, years_simulated, results_enduse_every_year, rs_enduses,
        ss_enduses, is_enduses, fig_name):
    """Plots summarised endues for the three sectors. Annual
    GWh are converted into GW.

    Arguments
    ----------
    data : dict
        Data container
    results_objects :

    enduses_data :

    Note
    ----
        -   Sum across all fueltypes

    # INFO Cannot plot a single year?
    """
    logging.info("plot annual demand for enduses for all submodels")

    submodels = ['residential', 'service', 'industry']
    nr_submodels = len(submodels)

    x_data = years_simulated
    y_data = np.zeros((nr_submodels, len(years_simulated)))

    # Set figure size
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(8, 8))

    ax = fig.add_subplot(1, 1, 1)

    for model_year, data_model_run in enumerate(
            results_enduse_every_year.values()):

        submodel = 0
        for fueltype_int in range(lookups['fueltypes_nr']):
            for enduse in rs_enduses:

                # Conversion: Convert gwh per years to gw
                yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
                yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
                y_data[submodel][model_year] += yearly_sum_twh  #yearly_sum_gw

        submodel = 1
        for fueltype_int in range(lookups['fueltypes_nr']):
            for enduse in ss_enduses:

                # Conversion: Convert gwh per years to gw
                yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
                yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
                y_data[submodel][model_year] += yearly_sum_twh  #yearly_sum_gw

        submodel = 2
        for fueltype_int in range(lookups['fueltypes_nr']):
            for enduse in is_enduses:

                # Conversion: Convert gwh per years to gw
                yearly_sum_gw = np.sum(data_model_run[enduse][fueltype_int])
                yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)
                y_data[submodel][model_year] += yearly_sum_twh  #yearly_sum_gw

    # Convert to stack
    y_stacked = np.row_stack((y_data))

    color_stackplots = ['darkturquoise', 'orange', 'firebrick']

    # ----------
    # Stack plot
    # ----------
    ax.stackplot(x_data, y_stacked, colors=color_stackplots)

    # ------------
    # Plot color legend with colors for every SUBMODEL
    # ------------
    plt.legend(submodels,
               ncol=1,
               prop={
                   'family': 'arial',
                   'size': 5
               },
               loc='best',
               frameon=False)

    # -------
    # Axis
    # -------
    plt.xticks(years_simulated, years_simulated)
    plt.axis('tight')

    # -------
    # Labels
    # -------
    plt.ylabel("TWh")
    plt.xlabel("year")
    plt.title("UK ED per sector")

    # Tight layout
    plt.margins(x=0)
    fig.tight_layout()

    # Save fig
    plt.savefig(fig_name)
    plt.close()
def run(years_simulated,
        results_enduse_every_year,
        enduses,
        color_list,
        fig_name,
        plot_legend=True):
    """Plots stacked energy demand

    Arguments
    ----------
    years_simulated : list
        Simulated years
    results_enduse_every_year : dict
        Results [year][enduse][fueltype_array_position]

    enduses :
    fig_name : str
        Figure name

    Note
    ----
        -   Sum across all fueltypes
        -   Not possible to plot single year

    https://matplotlib.org/examples/pylab_examples/stackplot_demo.html
    """
    print("...plot stacked enduses")
    nr_of_modelled_years = len(years_simulated)

    x_data = np.array(years_simulated)

    y_value_arrays = []
    legend_entries = []

    for enduse in enduses:
        legend_entries.append(enduse)

        y_values_enduse_yrs = np.zeros((nr_of_modelled_years))

        for year_array_nr, model_year in enumerate(
                results_enduse_every_year.keys()):

            # Sum across all fueltypes
            tot_across_fueltypes = np.sum(
                results_enduse_every_year[model_year][enduse])

            # Conversion: Convert GWh per years to GW
            yearly_sum_twh = conversions.gwh_to_twh(tot_across_fueltypes)

            logging.debug("... model_year {} enduse {}  twh {}".format(
                model_year, enduse, np.sum(yearly_sum_twh)))

            if yearly_sum_twh < 0:
                raise Exception("no minus values allowed {}  {}  {}".format(
                    enduse, yearly_sum_twh, model_year))

            y_values_enduse_yrs[year_array_nr] = yearly_sum_twh

        # Add array with values for every year to list
        y_value_arrays.append(y_values_enduse_yrs)

    # Try smoothing line
    try:
        x_data_smoothed, y_value_arrays_smoothed = basic_plot_functions.smooth_data(
            x_data, y_value_arrays, num=40000)
    except:
        x_data_smoothed = x_data
        y_value_arrays_smoothed = y_value_arrays

    # Convert to stacked
    y_stacked = np.row_stack((y_value_arrays_smoothed))

    # Set figure size
    fig = plt.figure(figsize=basic_plot_functions.cm2inch(8, 8))

    ax = fig.add_subplot(1, 1, 1)

    # ----------
    # Stack plot
    # ----------
    color_stackplots = color_list[:len(enduses)]

    ax.stackplot(x_data_smoothed,
                 y_stacked,
                 alpha=0.8,
                 colors=color_stackplots)

    if plot_legend:
        plt.legend(legend_entries,
                   prop={
                       'family': 'arial',
                       'size': 5
                   },
                   ncol=2,
                   loc='upper center',
                   bbox_to_anchor=(0.5, -0.1),
                   frameon=False,
                   shadow=True)

    # -------
    # Axis
    # -------
    year_interval = 10
    major_ticks = np.arange(years_simulated[0],
                            years_simulated[-1] + year_interval, year_interval)

    plt.xticks(major_ticks, major_ticks)

    plt.ylim(ymax=500)
    #yticks = [100, 200, 300, 400, 500]
    #plt.yticks(yticks, yticks)
    # -------
    # Labels
    # -------
    plt.ylabel("TWh", fontsize=10)
    plt.xlabel("Year", fontsize=10)
    #plt.title("ED whole UK", fontsize=10)

    # Tight layout
    fig.tight_layout()

    plt.margins(x=0)
    plt.savefig(fig_name)
    plt.close()
def run(data_input, fueltype_str, fig_name):
    """Plot peak demand and total demand over time in same plot
    """
    statistics_to_print = []

    # Select period and fueltype
    fueltype_int = tech_related.get_fueltype_int(fueltype_str)

    # -----------------------------------------------------------
    # Modelled years
    # -----------------------------------------------------------

    # List of selected data for every weather year (which is then converted to array)
    weather_yrs_total_demand = []
    weather_yrs_peak_demand = []

    nr_weather_yrs = list(data_input.keys())
    statistics_to_print.append("_____________________________")
    statistics_to_print.append("Weather years")
    statistics_to_print.append(str(data_input.keys()))

    # Iterate weather years
    for weather_yr, data_weather_yr in data_input.items():

        total_demands = []
        peak_demands = []
        sim_yrs = []
        for sim_yr in data_weather_yr.keys():
            sim_yrs.append(sim_yr)
            data_input_fueltype = data_weather_yr[sim_yr][
                fueltype_int]  # Select fueltype

            # sum total annual demand and convert gwh to twh
            sum_gwh_y = np.sum(data_input_fueltype)
            sum_thw_y = conversions.gwh_to_twh(sum_gwh_y)

            # Get peak
            peak_h = np.max(data_input_fueltype.reshape(8760))

            total_demands.append(sum_thw_y)
            peak_demands.append(peak_h)

        weather_yrs_total_demand.append(total_demands)
        weather_yrs_peak_demand.append(peak_demands)

    columns = sim_yrs

    # Convert to array
    weather_yrs_total_demand = np.array(weather_yrs_total_demand)
    weather_yrs_peak_demand = np.array(weather_yrs_peak_demand)

    # Calculate std per simulation year
    std_total_demand = list(np.std(weather_yrs_total_demand,
                                   axis=0))  # across columns calculate std
    std_peak_demand = list(np.std(weather_yrs_peak_demand,
                                  axis=0))  # across columns calculate std

    # Create dataframe
    if len(nr_weather_yrs) > 2:

        # Create dataframes
        df_total_demand = pd.DataFrame(weather_yrs_total_demand,
                                       columns=columns)
        df_peak = pd.DataFrame(weather_yrs_peak_demand, columns=columns)

        # Calculate quantiles
        quantile_95 = 0.95
        quantile_05 = 0.05

        # Calculate quantiles
        df_total_demand_q_95 = df_total_demand.quantile(quantile_95)
        df_total_demand_q_05 = df_total_demand.quantile(quantile_05)
        df_peak_q_95 = df_peak.quantile(quantile_95)
        df_peak_q_05 = df_peak.quantile(quantile_05)

        # convert to list
        df_total_demand_q_95 = df_total_demand_q_95.tolist()
        df_total_demand_q_05 = df_total_demand_q_05.tolist()
        df_peak_q_95 = df_peak_q_95.tolist()
        df_peak_q_05 = df_peak_q_05.tolist()
        #df_peak = df_peak.T #All indivdiual values
    else:
        #df_total_demand = weather_yrs_total_demand
        #df_peak = weather_yrs_peak_demand
        pass

    # -------------------
    # Base year data (2015)
    # -------------------
    # total demand
    tot_demand_twh_2015 = []
    for sim_yr, data_sim_yr in data_input[2015].items():
        gwh_2015_y = np.sum(data_sim_yr[fueltype_int])
        twh_2015_y = conversions.gwh_to_twh(gwh_2015_y)
        tot_demand_twh_2015.append(twh_2015_y)

    # peak
    df_peak_2015 = []
    for sim_yr, data_sim_yr in data_input[2015].items():
        peak_gwh_2015_y = np.max(data_sim_yr[fueltype_int])
        df_peak_2015.append(peak_gwh_2015_y)

    # ---------------
    # Smoothing lines
    # ---------------
    if len(nr_weather_yrs) > 2:
        try:
            period_h_smoothed, tot_demand_twh_2015_smoothed = basic_plot_functions.smooth_data(
                columns, tot_demand_twh_2015, num=40000)
            period_h_smoothed, df_total_demand_q_95_smoothed = basic_plot_functions.smooth_data(
                list(columns), df_total_demand_q_95, num=40000)
            period_h_smoothed, df_total_demand_q_05_smoothed = basic_plot_functions.smooth_data(
                columns, df_total_demand_q_05, num=40000)
            period_h_smoothed, df_peak_q_95_smoothed = basic_plot_functions.smooth_data(
                list(columns), df_peak_q_95, num=40000)
            period_h_smoothed, df_peak_q_05_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_q_05, num=40000)
            period_h_smoothed, df_peak_2015_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_2015, num=40000)
        except:
            period_h_smoothed = columns
            df_total_demand_q_95_smoothed = df_total_demand_q_95
            df_total_demand_q_05_smoothed = df_total_demand_q_05
            df_peak_q_95_smoothed = df_peak_q_95
            df_peak_q_05_smoothed = df_peak_q_05
            tot_demand_twh_2015_smoothed = tot_demand_twh_2015
            df_peak_2015_smoothed = df_peak_2015
    else:
        try:
            period_h_smoothed, tot_demand_twh_2015_smoothed = basic_plot_functions.smooth_data(
                columns, tot_demand_twh_2015, num=40000)
            period_h_smoothed, df_peak_2015_smoothed = basic_plot_functions.smooth_data(
                columns, df_peak_2015, num=40000)
        except:
            period_h_smoothed = columns
            tot_demand_twh_2015_smoothed = tot_demand_twh_2015
            df_peak_2015_smoothed = df_peak_2015

    # --------------
    # Two axis figure
    # --------------
    fig, ax1 = plt.subplots(figsize=basic_plot_functions.cm2inch(15, 10))

    ax2 = ax1.twinx()

    # Axis label
    ax1.set_xlabel('Years')
    ax2.set_ylabel('Peak hour {} demand (GW)'.format(fueltype_str),
                   color='black')
    ax1.set_ylabel('Total {} demand (TWh)'.format(fueltype_str), color='black')

    # Make the y-axis label, ticks and tick labels match the line color.¨
    color_axis1 = 'lightgrey'
    color_axis2 = 'blue'

    ax1.tick_params('y', colors='black')
    ax2.tick_params('y', colors='black')

    if len(nr_weather_yrs) > 2:

        # -----------------
        # Uncertainty range total demand
        # -----------------
        '''ax1.plot(
            period_h_smoothed,
            df_total_demand_q_05_smoothed,
            color='tomato', linestyle='--', linewidth=0.5, label="0.05_total_demand")'''
        '''ax1.plot(
            period_h_smoothed,
            df_total_demand_q_95_smoothed,
            color=color_axis1, linestyle='--', linewidth=0.5, label="0.95_total_demand")

        ax1.fill_between(
            period_h_smoothed, #x
            df_total_demand_q_95_smoothed,  #y1
            df_total_demand_q_05_smoothed,  #y2
            alpha=.25,
            facecolor=color_axis1,
            label="uncertainty band demand")'''

        # -----------------
        # Uncertainty range peaks
        # -----------------
        ##ax2.plot(period_h_smoothed, df_peak_q_05_smoothed, color=color_axis2, linestyle='--', linewidth=0.5, label="0.05_peak")
        ##ax2.plot(period_h_smoothed, df_peak_q_95_smoothed, color=color_axis2, linestyle='--', linewidth=0.5, label="0.95_peak")
        ax2.plot(period_h_smoothed,
                 df_peak_2015_smoothed,
                 color=color_axis2,
                 linestyle="--",
                 linewidth=0.4)

        # Error bar of bar charts
        ax2.errorbar(columns,
                     df_peak_2015,
                     linewidth=0.5,
                     color='black',
                     yerr=std_peak_demand,
                     linestyle="None")

        # Error bar bar plots
        ax1.errorbar(columns,
                     tot_demand_twh_2015,
                     linewidth=0.5,
                     color='black',
                     yerr=std_total_demand,
                     linestyle="None")
        '''ax2.fill_between(
            period_h_smoothed, #x
            df_peak_q_95_smoothed,  #y1
            df_peak_q_05_smoothed,  #y2
            alpha=.25,
            facecolor="blue",
            label="uncertainty band peak")'''

    # Total demand bar plots
    ##ax1.plot(period_h_smoothed, tot_demand_twh_2015_smoothed, color='tomato', linestyle='-', linewidth=2, label="tot_demand_weather_yr_2015")
    ax1.bar(columns,
            tot_demand_twh_2015,
            width=2,
            alpha=1,
            align='center',
            color=color_axis1,
            label="total {} demand".format(fueltype_str))

    statistics_to_print.append("_____________________________")
    statistics_to_print.append("total demand per model year")
    statistics_to_print.append(str(tot_demand_twh_2015))

    # Line of peak demand
    #ax2.plot(columns, df_peak, color=color_axis2, linestyle='--', linewidth=0.5, label="peak_0.95")
    ax2.plot(period_h_smoothed,
             df_peak_2015_smoothed,
             color=color_axis2,
             linestyle='-',
             linewidth=2,
             label="{} peak demand (base weather yr)".format(fueltype_str))

    statistics_to_print.append("_____________________________")
    statistics_to_print.append("peak demand per model year")
    statistics_to_print.append(str(df_peak_2015))

    # Scatter plots of peak demand
    ax2.scatter(columns,
                df_peak_2015,
                marker='o',
                s=20,
                color=color_axis2,
                alpha=1)

    ax1.legend(prop={
        'family': 'arial',
        'size': 10
    },
               loc='upper center',
               bbox_to_anchor=(0.9, -0.1),
               frameon=False,
               shadow=True)

    ax2.legend(prop={
        'family': 'arial',
        'size': 10
    },
               loc='upper center',
               bbox_to_anchor=(0.1, -0.1),
               frameon=False,
               shadow=True)

    # More space at bottom
    #fig.subplots_adjust(bottom=0.4)
    fig.tight_layout()

    plt.savefig(fig_name)
    plt.close()

    # Write info to txt
    write_data.write_list_to_txt(
        os.path.join(fig_name.replace(".pdf", ".txt")), statistics_to_print)
    print("--")
def run(results, lookups, fig_name, plotshow=False):
    """Plot lines with total energy demand for all enduses
    per fueltype over the simluation period. Annual GWh
    are converted into GW.

    Arguments
    ---------
    results : dict
        Results for every year and fueltype (yh)
    lookups : dict
        Lookup fueltypes
    fig_name : str
        Figure name

    Note
    ----
    Values are divided by 1'000
    """
    print("... plot fuel per fueltype for whole country over annual timesteps")

    # Set figure size
    plt.figure(figsize=basic_plot_functions.cm2inch(14, 8))

    # Initialise (number of enduses, number of hours to plot)
    y_values_fueltype = {}

    for fueltype_str, fueltype_int in lookups['fueltypes'].items():

        # Read out fueltype specific max h load
        data_years = {}
        for year, data_year in results.items():
            tot_gwh_fueltype_y = np.sum(data_year[fueltype_int])

            #Conversion: Convert gwh per years to gw
            yearly_sum_gw = tot_gwh_fueltype_y

            yearly_sum_twh = conversions.gwh_to_twh(yearly_sum_gw)

            data_years[year] = yearly_sum_twh  #yearly_sum_gw

        y_values_fueltype[fueltype_str] = data_years

    # -----------------
    # Axis
    # -----------------
    base_yr, year_interval = 2015, 5
    end_yr = list(results.keys())

    major_ticks = np.arange(base_yr, end_yr[-1] + year_interval, year_interval)

    plt.xticks(major_ticks, major_ticks)

    # ----------
    # Plot lines
    # ----------
    color_list_selection = plotting_styles.color_list_selection()

    for fueltype_str, fuel_fueltype_yrs in y_values_fueltype.items():

        if len(np.array(list(fuel_fueltype_yrs.values()))) > 2:
            smooth_x_line_data, smooth_y_line_data = basic_plot_functions.smooth_line(
                np.array(list(fuel_fueltype_yrs.keys())),
                np.array(list(fuel_fueltype_yrs.values())))
        else:
            smooth_x_line_data = list(fuel_fueltype_yrs.keys())
            smooth_y_line_data = list(fuel_fueltype_yrs.values())

        plt.plot(
            smooth_x_line_data,  # years
            smooth_y_line_data,  # yearly data per fueltype
            color=str(color_list_selection.pop()),
            label=fueltype_str)

    # ----
    # Axis
    # ----
    plt.ylim(ymin=0)  #no upper limit to xmax

    # ------------
    # Plot legend
    # ------------
    plt.legend(ncol=2,
               loc=2,
               prop={
                   'family': 'arial',
                   'size': 10
               },
               frameon=False)

    # ---------
    # Labels
    # ---------
    plt.ylabel("TWh")
    plt.xlabel("year")
    plt.title("tot annual ED per fueltype")

    # Tight layout
    plt.tight_layout()
    plt.margins(x=0)

    plt.savefig(fig_name)

    if plotshow:
        plt.show()
        plt.close()
    else:
        plt.close()