Skip to content

som_plots

Methods to plot SOM results.

build_display(res, data, out_dir, use_parallel_processing=False, selection=None)

Constructs plots to visualize results.

Parameters:

Name Type Description Default
res dict

SOM results.

required
data dict

SOM input data.

required
out_dir str

plot output directory.

required
use_parallel_processing bool

toggle for multiprocessing.

False
selection dict

filtering options.

None
Source code in src/som_plots.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
def build_display(res: dict[str, dict[str, pd.DataFrame]], data: dict[str, pd.DataFrame], out_dir: str, use_parallel_processing: bool = False, selection: dict[str, list] = None):
    """
    Constructs plots to visualize results.

    Arguments:
        res (dict): SOM results.
        data (dict): SOM input data.
        out_dir (str): plot output directory.
        use_parallel_processing (bool): toggle for multiprocessing.
        selection (dict): filtering options.
    """
    res = copy.deepcopy(res)
    data = copy.deepcopy(data)

    if selection is not None:
        print('\t\tFiltering results...')
        res = filter_results(res, selection)
        data = filter_ids(data, selection)

    areas = data['area']['ID']

    cpu_count = multiprocessing.cpu_count()     # available cpu cores
    with multiprocessing.Manager() as manager:
        progress = manager.Namespace()
        progress.current = 0
        progress.total = len(areas)
        lock = manager.Lock()
        if use_parallel_processing:
            with multiprocessing.Pool(processes=(min(cpu_count - 2, len(areas)))) as pool:
                jobs = [(area, res, data, out_dir, progress, lock) for area in areas]
                progress.current = 0
                display_progress(progress.current / progress.total, text='\t\tTPL: ')
                pool.starmap(plot_total_pressure_load_levels, jobs)
                display_progress(progress.current / progress.total, text='\t\tTPL: ')
                progress.current = 0
                display_progress(progress.current / progress.total, text='\n\t\tPressures: ')
                pool.starmap(plot_pressure_levels, jobs)
                display_progress(progress.current / progress.total, text='\t\tPressures: ')
                progress.current = 0
                display_progress(progress.current / progress.total, text='\n\t\tThresholds: ')
                pool.starmap(plot_thresholds, jobs)
                display_progress(progress.current / progress.total, text='\t\tThresholds: ')
                progress.current = 0
                display_progress(progress.current / progress.total, text='\n\t\tStatePressures: ')
                pool.starmap(plot_state_pressure_levels, jobs)
                display_progress(progress.current / progress.total, text='\t\tStatePressures: ')
                progress.current = 0
                display_progress(progress.current / progress.total, text='\n\t\tActivityContributions: ')
                pool.starmap(plot_activity_contributions, jobs)
                display_progress(progress.current / progress.total, text='\t\tActivityContributions: ')
                progress.current = 0
                display_progress(progress.current / progress.total, text='\n\t\tPressureContributions: ')
                pool.starmap(plot_pressure_contributions, jobs)
                display_progress(progress.current / progress.total, text='\t\tPressureContributions: ')
        else:
            progress.current = 0
            display_progress(progress.current / progress.total, text='\t\tTPL: ')
            for area in areas:
                plot_total_pressure_load_levels(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tTPL: ')
            progress.current = 0
            display_progress(progress.current / progress.total, text='\n\t\tPressures: ')
            for area in areas:
                plot_pressure_levels(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tPressures: ')
            progress.current = 0
            display_progress(progress.current / progress.total, text='\n\t\tThresholds: ')
            for area in areas:
                plot_thresholds(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tThresholds: ')
            progress.current = 0
            display_progress(progress.current / progress.total, text='\n\t\tStatePressures: ')
            for area in areas:
                plot_state_pressure_levels(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tStatePressures: ')
            progress.current = 0
            display_progress(progress.current / progress.total, text='\n\t\tActivityContributions: ')
            for area in areas:
                plot_activity_contributions(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tActivityContributions: ')
            progress.current = 0
            display_progress(progress.current / progress.total, text='\n\t\tPressureContributions: ')
            for area in areas:
                plot_pressure_contributions(area, res, data, out_dir, progress, lock)
            display_progress(progress.current / progress.total, text='\t\tPressureContributions: ')

    #
    # Measure effects
    #

    print('\n\t\tMeasure effects...')

    # plot settings
    capsize = 3
    capthick = 1
    elinewidth = 1
    ecolor = 'salmon'
    label_angle = 60
    char_limit = 25
    bar_width = 0.4
    edge_color = 'black'

    fig, ax = plt.subplots(figsize=(100, 14), constrained_layout=True)

    bar_width = 0.8
    edge_color = 'black'
    activity_font_size = 8

    # adjust data
    df = res['MeasureEffects']['Mean'].merge(res['MeasureEffects']['Error'], on=['measure', 'pressure', 'state', 'activity'], how='left', suffixes=('_mean', '_error'))
    df = df.sort_values(by=['measure', 'pressure', 'state', 'activity'])
    suffixes = ('', '_name')
    for col in ['measure', 'activity', 'pressure', 'state']:
        df = df.merge(data[col].loc[:, [col, 'ID']], left_on=col, right_on='ID', how='left', suffixes=suffixes)
        df = df.drop(columns=[col, 'ID'])
        df = df.rename(columns={col+'_name': col})
        df.loc[:, col] = np.array([(x[:char_limit]+'...' if len(x) > char_limit else x) if type(x) == str else 'All' for x in df.loc[:, col].values])
    df['index'] = np.arange(len(df))
    x_ticks = {x: df[df['measure'] == x]['index'].mean() for x in df['measure'].unique()}

    # set colors
    df['color_key'] = df['pressure'].astype(str) + '_' + df['state'].astype(str)
    unique_keys = df['color_key'].unique()
    colors = plt.cm.viridis(np.linspace(0, 1, len(unique_keys)))
    color_map = {key: colors[i] for i, key in enumerate(unique_keys)}

    # create plot
    for key in unique_keys:
        subset = df[df['color_key'] == key]
        bars = ax.bar(subset['index'], subset['reduction_mean'] * 100, width=bar_width, color=color_map[key], label=key if key not in ax.get_legend_handles_labels()[1] else '', edgecolor=edge_color)
        ax.errorbar(subset['index'], subset['reduction_mean'] * 100, yerr=subset['reduction_error'] * 100, linestyle='None', marker='None', capsize=capsize, capthick=capthick, elinewidth=elinewidth, ecolor=ecolor)
        for bar, (_, row) in zip(bars, subset.iterrows()):
            ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() / 2, str(row['activity']), 
                    ha='center', va='center', rotation=90, fontsize=activity_font_size, color='white')

    ax.set_xlabel('Measure')
    ax.set_ylabel('Reduction effect (%)')
    ax.set_title(f'Measure Reduction Effects')
    ax.set_xticks(list(x_ticks.values()), list(x_ticks.keys()), rotation=label_angle, ha='right')
    ax.yaxis.grid(True, linestyle='--', color='lavender')
    ax.legend(title='Pressure/State', bbox_to_anchor=(1.05, 1), loc='upper left')

    # adjust axis limits
    x_lim = [- 0.5, len(df) - 0.5]
    ax.set_xlim(x_lim)
    y_lim = [0, 100]
    ax.set_ylim(y_lim)

    # export
    for area in areas:
        area_name = data['area'].loc[areas == area, 'area'].values[0]
        temp_dir = os.path.join(out_dir, f'area_{area}_{area_name}')
        plt.savefig(os.path.join(temp_dir, f'area_{area}_{area_name}_MeasureEffects.png'), dpi=200)

    plt.close(fig)

filter_ids(input_data, selection)

Filter input data id dataframes.

Parameters:

Name Type Description Default
input_data dict

SOM input data.

required
selection dict

filtering options.

required

Returns:

Name Type Description
input_data dict

filtered input data.

Source code in src/som_plots.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def filter_ids(input_data: dict[str, pd.DataFrame], selection: dict[str, list]) -> dict[str, pd.DataFrame]:
    """
    Filter input data id dataframes.

    Arguments:
        input_data (dict): SOM input data.
        selection (dict): filtering options.

    Returns:
        input_data (dict): filtered input data.
    """
    for key, values in [
        ('measure', selection['measure']), 
        ('activity', selection['activity']), 
        ('pressure', selection['pressure']), 
        ('state', selection['state']), 
        ('area', selection['area'])
    ]:
        if values != []:
            input_data[key] = input_data[key].loc[input_data[key]['ID'].isin(values), :]
    return input_data

filter_results(res, selection)

Filter results for more selective output.

Parameters:

Name Type Description Default
res dict

SOM results.

required
selection dict

filtering options.

required

Returns:

Name Type Description
res dict

filtered results.

Source code in src/som_plots.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def filter_results(res: dict[str, pd.DataFrame], selection: dict[str, list]) -> dict[str, pd.DataFrame]:
    """
    Filter results for more selective output.

    Arguments:
        res (dict): SOM results.
        selection (dict): filtering options.

    Returns:
        res (dict): filtered results.
    """
    # Pressure, TPL, TPLRed, Thresholds
    for key, values in [
        ('Pressure', selection['pressure']), 
        ('TPL', selection['state']), 
        ('TPLRed', selection['state']), 
        ('Thresholds', selection['state'])
    ]:
        for r in ['Mean', 'Error']:
            if values != []:
                if selection['area'] != []:
                    res[key][r] = res[key][r].loc[res[key][r]['ID'].isin(values), ['ID'] + selection['area']]
                else:
                    res[key][r] = res[key][r].loc[res[key][r]['ID'].isin(values), :]
    # StatePressure
    if selection['pressure'] != []:
        for s in res['StatePressure']:
            for r in ['Mean', 'Error']:
                if selection['area'] != []:
                    res['StatePressure'][s][r] = res['StatePressure'][s][r].loc[res['StatePressure'][s][r]['ID'].isin(selection['pressure']), ['ID'] + selection['area']]
                else:
                    res['StatePressure'][s][r] = res['StatePressure'][s][r].loc[res['StatePressure'][s][r]['ID'].isin(selection['pressure']), :]
    # MeasureEffects, ActivityContributions, PressureContributions
    for key, cols in {
        'MeasureEffects': {
            'measure': selection['measure'], 
            'activity': selection['activity'], 
            'pressure': selection['pressure'], 
            'state': selection['state']
        }, 
        'ActivityContributions': {
            'activity': selection['activity'], 
            'pressure': selection['pressure'], 
            'area_id': selection['area']
        }, 
        'PressureContributions': {
            'state': selection['state'], 
            'pressure': selection['pressure'], 
            'area_id': selection['area']
        }
    }.items():
        for r in ['Mean', 'Error']:
            for col, values in cols.items():
                if values != []:
                    res[key][r] = res[key][r].loc[res[key][r][col].isin(values), :]
    return res

plot_activity_contributions(area, res, data, out_dir, progress, lock)

Plots activity contributions.

Source code in src/som_plots.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def plot_activity_contributions(area, res, data, out_dir, progress, lock):
    """
    Plots activity contributions.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_dir = os.path.join(out_dir, f'area_{area}_{area_name}', 'contributions', 'activity')
    os.makedirs(out_dir, exist_ok=True)

    # plot settings
    char_limit = 25

    for pressure in res['ActivityContributions']['Mean']['pressure'].unique():
        pressure_name = data['pressure'].loc[data['pressure']['ID'] == pressure, 'pressure'].values[0]

        out_path = os.path.join(out_dir, f'area_{area}_{area_name}_pressure_{pressure}_ActivityContributions.png')

        fig, ax = plt.subplots(figsize=(12, 9), constrained_layout=True)

        # adjust data
        suffixes = ('_mean', '_error')
        df = pd.merge(res['ActivityContributions']['Mean'].loc[:, :], res['ActivityContributions']['Error'].loc[:, :], on=['activity', 'pressure', 'area_id'], suffixes=suffixes)
        contributions = df.loc[(df['area_id'] == area) & (df['pressure'] == pressure), :]
        labels = contributions['activity']
        labels = contributions['activity'].apply(lambda x: data['activity'].loc[data['activity']['ID'] == x, 'activity'].values[0])
        labels = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in labels])     # limit characters to char_limit
        vals = contributions['contribution_mean'] * 100    # convert to %

        # create plot
        ax.pie(vals, labels=labels, autopct='%1.1f%%')
        ax.set_title(f'Activity Contributions to Pressure ({pressure_name})\n({area_name})')

        # export
        plt.savefig(out_path, dpi=200)
        plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tActivityContributions: ')

plot_pressure_contributions(area, res, data, out_dir, progress, lock)

Plots pressure contributions.

Source code in src/som_plots.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def plot_pressure_contributions(area, res, data, out_dir, progress, lock):
    """
    Plots pressure contributions.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_dir = os.path.join(out_dir, f'area_{area}_{area_name}', 'contributions', 'pressure')
    os.makedirs(out_dir, exist_ok=True)

    # plot settings
    char_limit = 25

    for state in res['PressureContributions']['Mean']['state'].unique():
        state_name = data['state'].loc[data['state']['ID'] == state, 'state'].values[0]

        out_path = os.path.join(out_dir, f'area_{area}_{area_name}_state_{state}_PressureContributions.png')

        fig, ax = plt.subplots(figsize=(12, 9), constrained_layout=True)

        # adjust data
        suffixes = ('_mean', '_error')
        df = pd.merge(res['PressureContributions']['Mean'].loc[:, :], res['PressureContributions']['Error'].loc[:, :], on=['state', 'pressure', 'area_id'], suffixes=suffixes)
        contributions = df.loc[(df['area_id'] == area) & (df['state'] == state) & (pd.notna(df['contribution_mean'])), :]
        if len(contributions) > 0:
            labels = contributions['pressure']
            labels = contributions['pressure'].apply(lambda x: data['pressure'].loc[data['pressure']['ID'] == x, 'pressure'].values[0])
            labels = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in labels])     # limit characters to char_limit
            vals = contributions['contribution_mean'] * 100    # convert to %

            # create plot
            ax.pie(vals, labels=labels, autopct='%1.1f%%')
            ax.set_title(f'Pressure Contributions to State ({state_name})\n({area_name})')

            # export
            plt.savefig(out_path, dpi=200)
        plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tPressureContributions: ')

plot_pressure_levels(area, res, data, out_dir, progress, lock)

Plots pressures.

Source code in src/som_plots.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def plot_pressure_levels(area, res, data, out_dir, progress, lock):
    """
    Plots pressures.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_path = os.path.join(out_dir, f'area_{area}_{area_name}', f'area_{area}_{area_name}_PressureLevels.png')
    os.makedirs(os.path.dirname(out_path), exist_ok=True)

    # plot settings
    marker = 's'
    markersize = 5
    markercolor = 'black'
    capsize = 3
    capthick = 1
    elinewidth = 1
    ecolor = 'salmon'
    label_angle = 60
    char_limit = 25

    fig, ax = plt.subplots(figsize=(25, 12), constrained_layout=True)

    # adjust data
    suffixes = ('_mean', '_error')
    df = pd.merge(res['Pressure']['Mean'].loc[:, ['ID', area]], res['Pressure']['Error'].loc[:, ['ID', area]], on='ID', suffixes=suffixes)
    x_vals = data['pressure'].loc[:, 'pressure'].values
    x_vals = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in x_vals])     # limit characters to char_limit
    y_vals = df[str(area)+'_mean'] * 100    # convert to %
    y_err = df[str(area)+'_error'] * 100    # conver to %

    # create plot
    ax.errorbar(np.arange(len(x_vals)), y_vals, yerr=y_err, linestyle='None', marker=marker, capsize=capsize, capthick=capthick, elinewidth=elinewidth, markersize=markersize, color=markercolor, ecolor=ecolor)
    ax.set_xlabel('Pressure')
    ax.set_ylabel('Level (%)')
    ax.set_title(f'Pressure Levels\n({area_name})')
    ax.set_xticks(np.arange(len(x_vals)), x_vals, rotation=label_angle, ha='right')
    ax.yaxis.grid(True, linestyle='--', color='lavender')

    # adjust axis limits
    x_lim = [- 0.5, len(x_vals) - 0.5]
    ax.set_xlim(x_lim)
    y_lim = [-5, 105]
    ax.set_ylim(y_lim)

    # export
    plt.savefig(out_path, dpi=200)
    plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tPressures: ')

plot_state_pressure_levels(area, res, data, out_dir, progress, lock)

Plots state pressures.

Source code in src/som_plots.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def plot_state_pressure_levels(area, res, data, out_dir, progress, lock):
    """
    Plots state pressures.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_dir = os.path.join(out_dir, f'area_{area}_{area_name}', 'state')
    os.makedirs(out_dir, exist_ok=True)

    # plot settings
    marker = 's'
    markersize = 5
    markercolor = 'black'
    capsize = 3
    capthick = 1
    elinewidth = 1
    ecolor = 'salmon'
    label_angle = 60
    char_limit = 25

    for state in res['StatePressure']:
        state_name = data['state'].loc[data['state']['ID'] == state, 'state'].values[0]

        out_path = os.path.join(out_dir, f'area_{area}_{area_name}_state_{state}_PressureLevels.png')

        fig, ax = plt.subplots(figsize=(25, 12), constrained_layout=True)

        # adjust data
        suffixes = ('_mean', '_error')
        df = pd.merge(res['StatePressure'][state]['Mean'].loc[:, ['ID', area]], res['StatePressure'][state]['Error'].loc[:, ['ID', area]], on='ID', suffixes=suffixes)
        x_vals = data['pressure'].loc[:, 'pressure'].values
        x_vals = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in x_vals])     # limit characters to char_limit
        y_vals = df[str(area)+'_mean'] * 100    # convert to %
        y_err = df[str(area)+'_error'] * 100    # conver to %

        # create plot
        ax.errorbar(np.arange(len(x_vals)), y_vals, yerr=y_err, linestyle='None', marker=marker, capsize=capsize, capthick=capthick, elinewidth=elinewidth, markersize=markersize, color=markercolor, ecolor=ecolor)
        ax.set_xlabel('Pressure')
        ax.set_ylabel('Level (%)')
        ax.set_title(f'Pressure Levels ({state_name})\n({area_name})')
        ax.set_xticks(np.arange(len(x_vals)), x_vals, rotation=label_angle, ha='right')
        ax.yaxis.grid(True, linestyle='--', color='lavender')

        # adjust axis limits
        x_lim = [- 0.5, len(x_vals) - 0.5]
        ax.set_xlim(x_lim)
        y_lim = [-5, 105]
        ax.set_ylim(y_lim)

        # export
        plt.savefig(out_path, dpi=200)
        plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tStatePressures: ')

plot_thresholds(area, res, data, out_dir, progress, lock)

Plots thresholds comparison.

Source code in src/som_plots.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def plot_thresholds(area, res, data, out_dir, progress, lock):
    """
    Plots thresholds comparison.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_path = os.path.join(out_dir, f'area_{area}_{area_name}', f'area_{area}_{area_name}_Thresholds.png')
    os.makedirs(os.path.dirname(out_path), exist_ok=True)

    # plot settings
    capsize = 3
    capthick = 1
    elinewidth = 1
    ecolor = 'salmon'
    label_angle = 60
    char_limit = 25
    bar_width = 0.4
    bar_color_1 = 'turquoise'
    bar_color_2 = 'seagreen'
    edge_color = 'black'

    fig, ax = plt.subplots(figsize=(16, 12), constrained_layout=True)

    # adjust data
    x_labels = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in data['state'].loc[:, 'state'].values])     # limit characters to char_limit
    x_vals = np.arange(len(x_labels))
    suffixes = ('_mean', '_error')
    df = pd.merge(res['TPLRed']['Mean'].loc[:, ['ID', area]], res['TPLRed']['Error'].loc[:, ['ID', area]], on='ID', suffixes=suffixes)
    y_vals_tpl = df[str(area)+'_mean'] * 100    # convert to %
    y_err_tpl = df[str(area)+'_error'] * 100    # conver to %
    df = pd.merge(res['Thresholds']['Mean'].loc[:, ['ID', area]], res['Thresholds']['Error'].loc[:, ['ID', area]], on='ID', suffixes=suffixes)
    y_vals_ges = df[str(area)+'_mean'] * 100    # convert to %
    y_err_ges = df[str(area)+'_error'] * 100    # convert to %

    # create plot
    label_tpl = 'Reduction with measures'
    ax.bar(x_vals-bar_width/2, y_vals_tpl, width=bar_width, align='center', color=bar_color_1, label=label_tpl, edgecolor=edge_color)
    ax.errorbar(x_vals-bar_width/2, y_vals_tpl, yerr=y_err_tpl, linestyle='None', marker='None', capsize=capsize, capthick=capthick, elinewidth=elinewidth, ecolor=ecolor)
    label_ges = 'Target'
    ax.bar(x_vals+bar_width/2, y_vals_ges, width=bar_width, align='center', color=bar_color_2, label=label_ges, edgecolor=edge_color)
    ax.errorbar(x_vals+bar_width/2, y_vals_ges, yerr=y_err_ges, linestyle='None', marker='None', capsize=capsize, capthick=capthick, elinewidth=elinewidth, ecolor=ecolor)
    ax.set_xlabel('Environmental State')
    ax.set_ylabel('Reduction (%)')
    ax.set_title(f'Total Pressure Load Reduction vs. GES Reduction Thresholds\n({area_name})')
    ax.set_xticks(x_vals, x_labels, rotation=label_angle, ha='right')
    ax.yaxis.grid(True, linestyle='--', color='lavender')
    ax.legend()

    # adjust axis limits
    x_lim = [- 0.5, len(x_vals) - 0.5]
    ax.set_xlim(x_lim)
    y_lim = [0, 100]
    ax.set_ylim(y_lim)

    # export
    plt.savefig(out_path, dpi=200)
    plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tThresholds: ')

plot_total_pressure_load_levels(area, res, data, out_dir, progress, lock)

Plots Total Pressure Load.

Source code in src/som_plots.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def plot_total_pressure_load_levels(area, res, data, out_dir, progress, lock):
    """
    Plots Total Pressure Load.
    """
    # create new directory for the plots
    area_name = data['area'].loc[data['area']['ID'] == area, 'area'].values[0]
    out_path = os.path.join(out_dir, f'area_{area}_{area_name}', f'area_{area}_{area_name}_TotalPressureLoadLevels.png')
    os.makedirs(os.path.dirname(out_path), exist_ok=True)

    # plot settings
    marker = 's'
    markersize = 5
    markercolor = 'black'
    capsize = 3
    capthick = 1
    elinewidth = 1
    ecolor = 'salmon'
    label_angle = 60
    char_limit = 25

    fig, ax = plt.subplots(figsize=(16, 12), constrained_layout=True)

    # adjust data
    suffixes = ('_mean', '_error')
    df = pd.merge(res['TPL']['Mean'].loc[:, ['ID', area]], res['TPL']['Error'].loc[:, ['ID', area]], on='ID', suffixes=suffixes)
    x_vals = data['state'].loc[:, 'state'].values
    x_vals = np.array([x[:char_limit]+'...' if len(x) > char_limit else x for x in x_vals])     # limit characters to char_limit
    y_vals = df[str(area)+'_mean'] * 100    # convert to %
    y_err = df[str(area)+'_error'] * 100    # conver to %

    # create plot
    ax.errorbar(np.arange(len(x_vals)), y_vals, yerr=y_err, linestyle='None', marker=marker, capsize=capsize, capthick=capthick, elinewidth=elinewidth, markersize=markersize, color=markercolor, ecolor=ecolor)
    ax.set_xlabel('Environmental State')
    ax.set_ylabel('Level (%)')
    ax.set_title(f'Total Pressure Load on Environmental States\n({area_name})')
    ax.set_xticks(np.arange(len(x_vals)), x_vals, rotation=label_angle, ha='right')
    ax.yaxis.grid(True, linestyle='--', color='lavender')

    # adjust axis limits
    x_lim = [- 0.5, len(x_vals) - 0.5]
    ax.set_xlim(x_lim)
    y_lim = [-5, 105]
    ax.set_ylim(y_lim)

    # export
    plt.savefig(out_path, dpi=200)
    plt.close(fig)

    with lock:
        progress.current += 1
        display_progress(progress.current / progress.total, text='\t\tTPL: ')