def draw_component_loss_barchart_v2(scenario,
                                    ctype_loss_vals_tot,
                                    ctype_loss_by_type,
                                    sc_haz_val_str,
                                    fig_name):
    """ Plots bar charts of direct economic losses for components types """

    bar_width = 0.3
    bar_offset = 0.03
    bar_clr_1 = spl.COLR_SET1[0]
    bar_clr_2 = spl.COLR_SET1[1]

    cpt = [spl.split_long_label(x,delims=[' ', '_'], max_chars_per_line=22)
           for x in ctype_resp_sorted.index.tolist()]
    pos = np.arange(0, len(cpt))

    fig = plt.figure(figsize=(4.5, len(pos)*0.6), facecolor='white')
    axes = fig.add_subplot(111, axisbg='white')

    # Economic loss:
    #   - Contribution to % loss of total system, by components type
    #   - Percentage econ loss for all components of a specific type

    axes.barh(
        pos-bar_width-bar_offset, ctype_loss_vals_tot, bar_width,
        color=bar_clr_1, alpha=0.85, edgecolor='bisque',
        label="Percentage loss of total system value (by component type)"
    )

    axes.barh(
        pos+bar_offset*2, ctype_loss_by_type, bar_width,
        color=bar_clr_2, alpha=0.85, edgecolor='bisque',
        label="Percentage loss for component type"
    )

    axes.tick_params(top='off', bottom='off', left='on', right='off')

    axes.set_xlim(0, max(ctype_loss_by_type))
    axes.set_xticklabels([''])
    axes.set_ylim([pos.max()+bar_width+0.4, pos.min()-bar_width-0.4])
    axes.set_yticks(pos)
    axes.set_yticklabels(cpt, size=11, color='k')
    axes.tick_params(top='off', bottom='off', left='on', right='off')

    for p, c, cv in zip(pos, cpt, ctype_loss_vals_tot):
        axes.annotate(('%0.1f' % np.float(cv))+'%',
                      xy=(cv+0.5, p-bar_offset-bar_width/2.0),
                      xycoords=('data', 'data'),
                      ha='left', va='center', size=11, color=bar_clr_1,
                      annotation_clip=False)

    for p, c, cv in zip(pos, cpt, ctype_loss_by_type):
        axes.annotate(('%0.1f' % np.float(cv))+'%',
                      xy=(cv+0.5, p+bar_offset*2+bar_width/2.0),
                      xycoords=('data', 'data'),
                      ha='left', va='center', size=11, color=bar_clr_2,
                      annotation_clip=False)

    axes.xaxis.set_ticks_position('none')
    spines_to_remove = ['left', 'top', 'right']
    for spine in spines_to_remove:
        axes.spines[spine].set_visible(False)

    axes.yaxis.grid(False)
    axes.xaxis.grid(False)

    axes.annotate(
        'Percentage Economic Loss by Component Type',
        xy=(0.0, -1.6), xycoords=('axes fraction', 'data'),
        ha='left', va='top',
        fontname='Open Sans', size=12, color='k', weight='bold',
        annotation_clip=False);
    axes.annotate(
        'Hazard Event: Earthquake ' + sc_haz_val_str + ' ' +
            scenario.intensity_measure_param,
        xy=(0.0, -1.1), xycoords=('axes fraction', 'data'),
        ha='left', va='top',
        fontname='Open Sans', size=12, color='grey', weight='bold',
        annotation_clip=False);

    axes.legend(loc=9, ncol=1, bbox_to_anchor=(0.46, -0.01),
                frameon=0, prop={'size':10})

    fig.savefig(
        os.path.join(scenario.output_path, fig_name),
        format='png', bbox_inches='tight', dpi=300
    )

    plt.close(fig)
def draw_component_failure_barchart(uncosted_comptypes,
                                    ctype_failure_mean,
                                    sc_haz_val_str,
                                    output_path,
                                    figname):

    comp_type_fail_sorted = \
        ctype_failure_mean.sort_values(by=[sc_haz_val_str], ascending=[0])

    for x in uncosted_comptypes:
        if x in comp_type_fail_sorted.index.tolist():
            comp_type_fail_sorted = comp_type_fail_sorted.drop(x, axis=0)

    cptypes = comp_type_fail_sorted.index.tolist()
    cpt = [spl.split_long_label(x,delims=[' ', '_'],max_chars_per_line=22)
           for x in cptypes]
    pos = np.arange(len(cptypes))
    cpt_failure_vals = comp_type_fail_sorted[sc_haz_val_str].values * 100

    fig = plt.figure(figsize=(10, len(pos)*0.6), facecolor='white')
    ax = fig.add_subplot(111, axisbg='white')
    bar_width = 0.6
    bar_clr = spl.COLR_SET3[4]    # dodgerblue

    ax.barh(pos, cpt_failure_vals, bar_width,
            color=bar_clr, edgecolor="bisque")

    # add the numbers to the side of each bar
    for p, c, cv in zip(pos, cptypes, cpt_failure_vals):
        plt.annotate(('%0.1f' % cv)+'%', xy=(cv+0.3, p+bar_width/2.0),
                     va='center', size=11, color='k')

    spines_to_remove = ['left', 'top', 'right', 'bottom']
    for spine in spines_to_remove:
        ax.spines[spine].set_visible(False)

    #cutomize ticks
    plt.gca().yaxis.tick_left()
    plt.yticks(pos + bar_width/2.0, cpt, size=11, color='k')
    xt = list(plt.xticks()[0])
    xt.append(max(xt)+10.0)
    plt.xticks(xt, [' '] * len(xt))
    ax.grid(False)
    ax.tick_params(top='off', bottom='off', left='off', right='off')

    #set plot limits
    plt.xlim(0, max(cpt_failure_vals)+5.0)
    plt.ylim(pos.max() + 1.0, pos.min() - 1.0)

    ax.annotate('Percentage Loss: Number of Components by Type',
                xy=(0.0, -1.3), xycoords=('axes fraction', 'data'),
                ha='left', va='top', annotation_clip=False,
                fontname='Open Sans', size=12, weight='bold', color='k');
    ax.annotate('Hazard Event: Earthquake ' + sc_haz_val_str + ' ' +
                    scenario.intensity_measure_param,
                xy=(0.0, -0.8), xycoords=('axes fraction', 'data'),
                ha='left', va='top', annotation_clip=False,
                fontname='Open Sans', size=12, weight='bold',
                color='darkgrey');

    fig.savefig(
        os.path.join(output_path, figname),
        format='png', bbox_inches='tight', dpi=300
    )

    plt.close(fig)
def draw_component_loss_barchart_v1(scenario,
                                    ctype_loss_vals_tot,
                                    ctype_loss_by_type,
                                    ctype_lossbytype_rank,
                                    sc_haz_val_str,
                                    fig_name):
    """ Plots bar charts of direct economic losses for components types """

    # Set color maps:
    clrmap1 = [plt.cm.autumn(1.2*x/float(len(ctype_loss_vals_tot)))
               for x in range(len(ctype_loss_vals_tot))]
    clrmap2 = [clrmap1[int(i)] for i in ctype_lossbytype_rank]

    a = 1.0     # transparency
    bar_width = 0.7
    yadjust = bar_width/2.0
    subplot_spacing = 0.6

    cpt = [spl.split_long_label(x,delims=[' ', '_'], max_chars_per_line=22)
           for x in ctype_resp_sorted.index.tolist()]
    pos = np.arange(0,len(cpt))

    fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True,
                                   facecolor='white',
                                   figsize=(12,len(pos)*0.6))
    fig.subplots_adjust(wspace=subplot_spacing)

    # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    # Economic loss contributed by all components of a specific type,
    # as a percentage of the value of the system

    ax1.barh(pos, ctype_loss_vals_tot, bar_width,
             color=clrmap1, edgecolor='bisque', alpha=a)
    ax1.set_xlim(0, max(ctype_loss_by_type))
    ax1.set_ylim(pos.max()+bar_width, pos.min()-bar_width)
    # ax1.grid(False)
    ax1.tick_params(top='off', bottom='off', left='off', right='on')
    ax1.set_title('Economic Loss \nPercent of System Value',
                     fontname='Open Sans', fontsize=12,
                     fontweight='bold', ha='right', x=1.00, y=0.99)

    # add the numbers to the side of each bar
    for p, c, cv in zip(pos, cpt, ctype_loss_vals_tot):
        ax1.annotate(('%0.1f' % np.float(cv))+'%',
                     xy=(cv+0.5, p+yadjust),
                     xycoords=('data', 'data'),
                     ha='right', va='center', size=11,
                     annotation_clip=False)

    ax1.xaxis.set_ticks_position('none')
    ax1.set_axis_off()

    # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
    # Aggregated economic loss for all components of a specific type

    ax2.barh(pos, ctype_loss_by_type, bar_width,
             color=clrmap2, edgecolor='bisque', alpha=a)
    ax2.set_xlim(0, max(ctype_loss_by_type))
    ax2.set_ylim(pos.max()+bar_width, pos.min()-bar_width)
    ax2.tick_params(top='off', bottom='off', left='on', right='off')
    ax2.set_title('Economic Loss \nPercent of Component Type Value',
                  fontname='Open Sans', fontsize=12,
                  fontweight='bold', ha='left', x=0,  y=0.99)

    for p, c, cv in zip(pos, cpt, ctype_loss_by_type):
        ax2.annotate(('%0.1f' % np.float(cv))+'%', xy=(cv+0.5, p+yadjust),
                     xycoords=('data', 'data'),
                     ha='left', va='center', size=11,
                     annotation_clip=False)

    ax2.xaxis.set_ticks_position('none')
    ax2.set_axis_off()

    # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

    ax1.invert_xaxis()

    for yloc, ylab in zip(pos, cpt):
        ax1.annotate(ylab,
                     xy=(1.0+subplot_spacing/2.0, yloc+yadjust),
                     xycoords=('axes fraction', 'data'),
                     ha='center', va='center', size=11, color='k',
                     annotation_clip=False)

    ax1.annotate('HAZARD EVENT\n' +
                 'Earthquake\n' +
                 sc_haz_val_str + ' ' + scenario.intensity_measure_param,
                 xy=(1.0 + subplot_spacing/2.0, -1.25),
                 xycoords=('axes fraction', 'data'),
                 ha='center', va='center', size=12,
                 fontname='Open Sans', color='darkgrey', weight='bold',
                 annotation_clip=False)

    fig.savefig(os.path.join(scenario.output_path, fig_name),
                format='png', bbox_inches='tight', dpi=300)

    plt.close(fig)