-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplotting.py
More file actions
1327 lines (1182 loc) · 54.8 KB
/
plotting.py
File metadata and controls
1327 lines (1182 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
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
65
66
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
118
119
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
176
177
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
239
240
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
280
281
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
322
323
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
479
480
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import geopandas as gpd
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
import pandas as pd
import os
import constants as c
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from pylab import *
import data_manipulation
import plotly.express as px
def world_data(data):
"""
merges the data to be plotted into a geopandas dataframe and selects relevant columns for plotting
:param data: the dataframe containing GCAM data to be plotted
:return: a pandas dataframe containing relevant year and column data
"""
world = gpd.read_file(c.GCAMConstants.processed_map_loc)
merged = pd.merge(world, data, on="GCAM", how='left')
merged = merged.replace(c.GCAMConstants.missing, np.nan)
return merged
def basin_data(data, column, title):
"""
merges the data to be plotted into a geopandas dataframe and selects relevant columns for plotting
:param data: the dataframe containing GCAM data to be plotted
:return: a pandas dataframe containing relevant year and column data
"""
# read in data
data["GLU"] = data["GLU"].str.replace("GLU00", "").str.replace("GLU0", "").str.replace("GLU", "") # remove GLU codes and leading 0s
data["GLU"] = data["GLU"].astype("int64")
data["SSP"] = "SSP1"
basins = gpd.read_file(c.GCAMConstants.basin_map_loc)
n_products = len(data["GCAM_subsector"].unique())
# set up plot info
cmap = plt.colormaps.get_cmap('viridis')
normalizer = Normalize(min(data[column]), max(data[column]))
im = cm.ScalarMappable(norm=normalizer, cmap=cmap)
# for each crop in the subsector
for i in data["GCAM_subsector"].unique():
fig, axs = plt.subplots(1, 1, sharex='all', sharey='all', gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
crop = data[data["GCAM_subsector"] == str(i)]
merged = pd.merge(basins, crop, left_on=["glu_id", "reg_id"], right_on=["GLU","GCAM_region_ID"], how='left')
merged = merged.replace(c.GCAMConstants.missing, np.nan)
if str(i) == "SugarCropC4":
subplot_title = title + " " + "Sugar Cane"
elif str(i) == "SugarCrop":
subplot_title = title + " " + "Sugar Beet and Sugar Crops"
else:
subplot_title = title + " " + str(i)
plot_world_on_axs(
map_plot=merged,
axs=axs,
cmap=cmap,
counter=0,
plot_title=subplot_title,
plotting_column=column,
ncol=1,
nrow=1,
normalizer=normalizer)
units = "kg/ha"
# update the figure with shared colorbar
lab = units
cax = fig.add_axes([0.08, 0.20, 0.02, 0.45])
fig.colorbar(im, cax=cax, shrink=0.5, orientation="vertical", label=lab)
# change figure size and dpi
fig.set_dpi(300)
plt.savefig("data/data_analysis/images/maps/" + subplot_title + ".png", dpi=300)
plt.show()
merged.drop("geometry",axis=1).to_csv("data/data_analysis/supplementary_tables/maps/" + subplot_title + ".csv")
def get_subplot_dimensions(list_products):
"""
returns the number of subplot dimensions based on the number of items being plotted
:param list_products: the list of things being plotted on one plot
:return: the number of rows and the number of columns for the plot
"""
if len(list_products) == 1:
return 1, 1
elif len(list_products) == 2:
return 2, 1
elif len(list_products) == 3:
return 2, 2
elif len(list_products) == 4:
return 2, 2
elif len(list_products) == 5 or len(list_products) == 6:
return 2, 3
elif len(list_products) == 7 or len(list_products) == 8:
return 2, 4
elif len(list_products) == 9:
return 3, 3
elif len(list_products) in [10, 11, 12]:
return 3, 4
elif len(list_products) in [13, 14, 15, 16]:
return 4, 4
elif len(list_products) in [17, 18, 19, 20]:
return 4, 5
else:
raise ValueError("too many products. Can only plot 20 products at a time")
def plot_world(dataframe, products, SSPS, groupby, column, years, title, RCP, nonBaselineScenario):
"""
control function for plotting any plot that is placed on a world map
:param years: the years for which the plot is to be evaluated
:param dataframe: the dataframe containing data to be plotted
:param products: the list of products that are to be plotted
:param SSPS: the list of SSPs by which the data is to be plotted
:param groupby: how the data should be grouped. Accepted values include "SSP", "product", "year"
:param column: the column on which the data should be filtered by product
:param title: the title of the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: shows the relevant plot
"""
if groupby == "SSP":
plot_world_by_SSP(dataframe, products, column, years, SSPS, title, RCP, nonBaselineScenario)
elif groupby == "product":
plot_world_by_products(dataframe, products, column, years, SSPS, title, RCP, nonBaselineScenario)
elif groupby == "year":
plot_world_by_years(dataframe, products, column, years, SSPS, title, RCP, nonBaselineScenario)
else:
raise ValueError("only 'SSP', 'product', and 'year' are considered valid groupings at this time")
def plot_world_by_SSP(dataframe, products, column, year, SSP, title, RCP, nonBaselineScenario):
"""
For a given product, plot its values in all SSPs for a given year
:param dataframe: the dataframe containing the data to be plotted
:param products: the product being plotted
:param column: the column in the dataframe containing the product
:param year: the year being chosen
:param title: the title for the plot
:param SSP: the set of shared socioeconomic pathways being used as evaluation
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
"""
for j in year:
for i in products:
try:
counter = 0
units = "N/A"
# get plot information
axs, cmap, fig, im, ncol, normalizer, nrow = create_subplots(
dataframe=dataframe,
inner_loop_set=SSP,
products=[i],
year=[j],
SSP=SSP,
product_column=column,
title=title)
for k in SSP:
subplot_title = str(k)
units = get_df_to_plot(
dataframe=dataframe,
ncol=ncol,
nrow=nrow,
fig=fig,
axs=axs,
cmap=cmap,
normalizer=normalizer,
counter=counter,
column=column,
products=i,
SSPs=k,
years=j,
subplot_title=subplot_title)
counter = counter + 1
# update the figure with shared colorbar
dl = len(SSP)
lab = units
add_colorbar_and_plot(axs, dl, fig, im, lab, ncol, nrow, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def plot_world_by_products(dataframe, products, column, year, SSP, title, RCP, nonBaselineScenario):
"""
For each SSP, plots all relevant products
:param SSP: the SSP scenario for the plot
:param year: The year of data to be plotted
:param dataframe: dataframe containing the data to be plotted
:param products: the data to be plotted
:param column: the column for which the data is to be filtered
:param title: the title for the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: shows the relevant plot
"""
for j in year:
for k in SSP:
try:
counter = 0
units = "N/A"
# get plot information
axs, cmap, fig, im, ncol, normalizer, nrow = create_subplots(
dataframe=dataframe,
inner_loop_set=products,
products=products,
year=[j],
SSP=[k],
product_column=column,
title=title)
# iterate through all subplots
for i in products:
subplot_title = str(i)
units = get_df_to_plot(
dataframe=dataframe,
ncol=ncol,
nrow=nrow,
fig=fig,
axs=axs,
cmap=cmap,
normalizer=normalizer,
counter=counter,
column=column,
products=i,
SSPs=k,
years=j,
subplot_title=subplot_title)
counter = counter + 1
# update the figure with shared colorbar
dl = len(products)
lab = units
add_colorbar_and_plot(axs, dl, fig, im, lab, ncol, nrow, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def axs_params(ax, plot_title):
"""
Provides uniform formatting for all axes
:param ax: the axis being formatted
:param plot_title: the title of the subplot
:return: N/A
"""
ax.tick_params(left=False, right=False, labelleft=False, labelbottom=False, bottom=False)
ax.margins(x=0.005, y=0.005)
ax.set_title(str(plot_title), fontsize=12)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
def plot_world_by_years(dataframe, products, column, year, SSP, title, RCP, nonBaselineScenario):
"""
For each SSP, plots all relevant products
:param SSP: the SSP scenario for the plot
:param year: The year of data to be plotted
:param dataframe: dataframe containing the data to be plotted
:param products: the data to be plotted
:param column: the column for which the data is to be filtered
:param title: the title for the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: shows the relevant plot
"""
for k in SSP:
for i in products:
try:
counter = 0
units = "N/A"
# get plot information
axs, cmap, fig, im, ncol, normalizer, nrow = create_subplots(
dataframe=dataframe,
inner_loop_set=year,
products=[i],
year=year,
SSP=[k],
product_column=column,
title=title)
# iterate through all subplots
for j in year:
subplot_title = str(j)
units = get_df_to_plot(
dataframe=dataframe,
ncol=ncol,
nrow=nrow,
fig=fig,
axs=axs,
cmap=cmap,
normalizer=normalizer,
counter=counter,
column=column,
products=i,
SSPs=k,
years=j,
subplot_title=subplot_title)
counter = counter + 1
# update the figure with shared colorbar
dl = len(year)
lab = str(units)
add_colorbar_and_plot(axs, dl, fig, im, lab, ncol, nrow, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def get_df_to_plot(dataframe, ncol, nrow, fig, axs, cmap, normalizer, counter, column, products, SSPs, years,
subplot_title):
"""
This method filters data and prepare it for plotting
:param dataframe: the data being plotted
:param ncol: the number of columns of subplots
:param nrow: the number of rows of subplots
:param fig: matplotlib fig
:param axs: the matplotlib axs being plotted
:param cmap: the colormap being used
:param normalizer: the normalizer bieng used
:param counter: the plot counter
:param column: the column on which the products are located
:param products: the products being plotted
:param SSPs: the SSPs being plotted
:param years: the years being plotted
:param subplot_title: the title for the subplot
:return: unit label for the subplot
"""
if column != "":
filter_data = dataframe[dataframe[[column]].isin([products]).any(axis=1)]
filter_data = filter_data[filter_data[['SSP']].isin([SSPs]).any(axis=1)]
else:
filter_data = dataframe
# if there is no data in the filter data, delete all following axis
if filter_data.empty:
if ncol == 1:
if nrow == 1:
fig.delaxes(axs)
else:
fig.delaxes(axs[counter])
else:
fig.delaxes(axs[int(counter / ncol), int(counter % ncol)])
else:
map_to_plot = world_data(filter_data)
plot_world_on_axs(
map_plot=map_to_plot,
axs=axs,
cmap=cmap,
counter=counter,
plot_title=subplot_title,
plotting_column=years,
ncol=ncol,
nrow=nrow,
normalizer=normalizer)
units = map_to_plot['Units'].unique()
for i in units:
if str(i) != "nan":
return str(i)
def plot_world_on_axs(map_plot, axs, cmap, counter, plot_title, plotting_column, ncol, normalizer, nrow):
"""
Plot the world map in a subplot
:param map_plot: the dataframe containing map info and the data being plotted
:param axs: the subplot axis on which the map is being plotted
:param cmap: the color map for the choropleth map
:param counter: the counter for which subplot is being counted
:param plot_title: the subplot title
:param plotting_column: the column containing data that is the basis of the choropleth map
:param ncol: the number of columns of subplots
:param normalizer: the data normalizer for the colorbar
:param nrow: the number of rows of subplots
:return: N/A
"""
if ncol == 1:
if nrow == 1:
map_plot.plot(
column=str(plotting_column),
missing_kwds=dict(color='grey', label='No Data'),
ax=axs,
cmap=cmap,
norm=normalizer)
axs_params(axs, plot_title)
else:
map_plot.plot(
column=str(plotting_column),
missing_kwds=dict(color='grey', label='No Data'),
ax=axs[int(counter / ncol)],
cmap=cmap,
norm=normalizer)
axs_params(axs[int(counter / ncol)], plot_title)
else:
map_plot.plot(
column=str(plotting_column),
missing_kwds=dict(color='grey', label='No Data'),
ax=axs[int(counter / ncol), int(counter % ncol)],
cmap=cmap,
norm=normalizer)
axs_params(axs[int(counter / ncol), int(counter % ncol)], plot_title)
def create_subplots(dataframe, inner_loop_set, products, year, SSP, product_column, title):
"""
Creates the boilerplate subplots and colorbars
:param inner_loop_set: the list of products being iterated over for the different subplots
:param SSP: The SSP of the scenario
:param product_column: The column on which the different products being graphed vary
:param dataframe: the dataframe being evaluated
:param products: the list of products being evaluated
:param year: the year in which the data is plotted
:param title: the title of the plot
:return: a set of figure objects
"""
# at this stage, if this df is empty, then we know that there is no material to plot
if dataframe.empty:
raise ValueError("These products" + str(products) + "do not exist in this dataframe")
df = dataframe.replace([np.inf, -np.inf], np.nan)
# get subplot size
nrow, ncol = get_subplot_dimensions(inner_loop_set)
# make plots and color scheme
fig, axs = plt.subplots(nrow, ncol, sharex='all', sharey='all', gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
cmap = plt.colormaps.get_cmap('viridis')
fig.suptitle(title)
normalizer = Normalize(min(df[str(i)].min() for i in year), max(df[str(i)].max() for i in year))
im = cm.ScalarMappable(norm=normalizer, cmap=cmap)
plt.xticks(range(min([int(y) for y in year]), max([int(y) for y in year])+1, 5))
return axs, cmap, fig, im, ncol, normalizer, nrow
def add_colorbar_and_plot(axs, datalength, fig, im, lab, ncol, nrow, fname, RCP, nonBaselineScenario):
"""
Adds the colorbar to the graph and produces output
:param axs: matplotlib axes
:param datalength: the length of the data being plotted
:param fig: matplotlib fig
:param im: matplotlib im
:param lab: label for the colorbar
:param ncol: number of rows of axes
:param nrow: number of columns of axes
:param fname: filename for output image
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: plotted figure
"""
del_axes_counter = 0
for i in range(nrow * ncol - datalength):
fig.delaxes(axs[int((datalength + i) / ncol), int((datalength + i) % ncol)])
del_axes_counter = del_axes_counter + 1
if nrow * ncol > datalength:
if del_axes_counter == 3:
axins1 = inset_axes(
axs[int((datalength + 1) / ncol), int((datalength + 1) % ncol)],
width=str(100 * del_axes_counter) + "%", # width: 50% of parent_bbox width
height="10%", # height: 5%
loc="center",
)
else:
axins1 = inset_axes(
axs[int(datalength / ncol), int(datalength % ncol)],
width=str(100 * del_axes_counter) + "%", # width: 50% of parent_bbox width
height="10%", # height: 5%
loc="center",
)
axins1.xaxis.set_ticks_position("bottom")
axins1.set_title(lab)
fig.colorbar(im, cax=axins1, orientation="horizontal")
elif ncol == 1:
if nrow == 1:
cax = fig.add_axes([0.9, 0.25, 0.02, 0.5])
fig.colorbar(im, cax=cax, shrink=0.6, orientation="vertical", label=lab)
else:
fig.colorbar(im, ax=axs[:], shrink=0.6, orientation="vertical", label=lab)
else:
fig.colorbar(im, ax=axs[nrow - 1, :], shrink=0.6, orientation="horizontal", label=lab)
# change figure size and dpi
fig.set_dpi(300)
if nrow * ncol == 6:
fig.set_size_inches(12, 4)
elif nrow * ncol == 8:
fig.set_size_inches(16, 5.1)
elif nrow * ncol == 20:
fig.set_size_inches(16, 9)
plt.savefig("data/data_analysis/images/" + str(RCP) + "/" + fname + ".png", dpi=300)
plt.show()
def plot_line_by_SSP(dataframe, products, column, SSP, differentiator, title, RCP, nonBaselineScenario):
"""
plots a line graph with different subplot for each SSP
:param dataframe: the dataframe with data to be plotted
:param products: the list of products to be plotted
:param column: the column i nthe dataframe in which the products can be found
:param SSP: the SSP scenario
:param differentiator: the column containing unique model names
:param title: the title of hte plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
try:
# get plot information
axs, cmap, fig, im, ncol, normalizer, nrow = create_subplots(
dataframe=dataframe,
inner_loop_set=products,
products=products,
year=c.GCAMConstants.biochar_x,
SSP=SSP,
product_column=column,
title=title)
# find the number of model versions
# get color scheme based on number of model versions
versions = dataframe[differentiator].unique()
colors, num_colors = get_colors(len(versions))
counter = 0
for i in products:
color_counter = 0
for k in SSP:
sub_color = 0
y = dataframe[(dataframe[column] == i) & (dataframe['SSP'] == k)]
if not y.empty:
# plot all versions in y
for j in y[differentiator].unique():
# get y label
if len(versions) > 1:
lab = str(k) + str(j)
else:
lab = str(k)
# get color
color = colors[color_counter * num_colors + sub_color]
sub_color = sub_color + 1
# get line of data to plot and plot it
df = y[y[differentiator] == j]
y_to_plot = df.values.tolist()[0][c.GCAMConstants.skip_years:c.GCAMConstants.skip_years + len(
c.GCAMConstants.biochar_x)] # only take the x values
plot_line_on_axs(
x=c.GCAMConstants.biochar_x,
y=y_to_plot,
lab=lab,
color=color,
axs=axs,
nrow=nrow,
ncol=ncol,
counter=counter)
# get units
units = y['Units'].unique()[0]
color_counter = color_counter + 1
l, h = finalize_line_subplot(axs, units, str(i), ncol, nrow, counter)
counter = counter + 1
finalize_line_plot(fig, h, l, axs, nrow, ncol, counter, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def finalize_line_plot(fig, handles, labels, axs, nrow, ncol, counter, title, RCP, nonBaselineScenario):
"""
adds a legend to the plot and removes unnecessary axes
:param fig: matplotlib figure
:param handles: matplotlib handles
:param labels: matplotlib labels
:param axs: maxplotlib axs
:param nrow: the number of rows of subplots
:param ncol: the number of columns of subplots
:param counter: the number of used subplots
:param title: the title of the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
if nrow * ncol == 1:
fig.legend(handles, labels, bbox_to_anchor=(1, .895), facecolor='white', framealpha=1)
plt.subplots_adjust(bottom=0.4, right=.7)
elif nrow * ncol == 2:
fig.legend(handles, labels, bbox_to_anchor=(1, .895), facecolor='white', framealpha=1)
plt.subplots_adjust(bottom=0.4, right=.7)
elif nrow * ncol == 4:
fig.legend(handles, labels, bbox_to_anchor=(0.6, 0.6), facecolor='white', framealpha=1)
plt.tight_layout()
elif nrow * ncol == 6 and counter == 5:
fig.legend(handles, labels, bbox_to_anchor=(0.9, 0.4), facecolor='white', framealpha=1)
plt.tight_layout()
elif nrow * ncol == 6:
fig.legend(handles, labels, bbox_to_anchor=(0.15, 0.54), facecolor='white', framealpha=1)
plt.tight_layout()
else:
fig.legend(handles, labels, bbox_to_anchor=(0.5, 1), facecolor='white', framealpha=1)
plt.tight_layout()
# remove unnecessary axes
for i in range(nrow * ncol - counter):
fig.delaxes(axs[int((counter + i) / ncol), int((counter + i) % ncol)])
plt.savefig("data/data_analysis/images/" + str(RCP) + "/" + title + ".png", dpi=300)
plt.show()
def plot_line_on_axs(x, y, lab, color, axs, nrow, ncol, counter):
"""
Plots a line on the axis
:param x: x values for the plot
:param y: y values for the plot
:param lab: label for the line
:param color: the color of the line
:param axs: the axis being plotted on
:param nrow: the number of rows of axes
:param ncol: the number of columns of axes
:param counter: the number of the current subplot
:return: N/A
"""
if ncol == 1:
if nrow == 1:
axs.plot(x, y, label=lab, color=color)
else:
axs[int(counter / ncol)].plot(x, y, label=lab, color=color)
else:
axs[int(counter / ncol), int(counter % ncol)].plot(x, y, label=lab, color=color)
def finalize_line_subplot(axs, ylabel, title, ncol, nrow, counter):
"""
Applies formatting to a subplot
:param axs: the axis of the subplot
:param ylabel: the label for the y-axis
:param title: the title of the graph
:param ncol: the number of rows of subplots
:param nrow: the number of columns of subplots
:param counter: the current subplot
:return: labels and handles of the subplot
"""
if ncol == 1:
if nrow == 1:
axs.set_ylabel(ylabel)
axs.set_xlabel("Year")
axs.set_title(title)
handles, labels = axs.get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
else:
axs[int(counter / ncol)].set_ylabel(ylabel)
axs[int(counter / ncol)].set_xlabel("Year")
axs[int(counter / ncol)].set_title(title)
handles, labels = axs[0].get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
else:
axs[int(counter / ncol), int(counter % ncol)].set_ylabel(ylabel)
axs[int(counter / ncol), int(counter % ncol)].set_title(title)
axs[int(counter / ncol), int(counter % ncol)].set_xlabel("Year")
handles, labels = axs[0, 0].get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
return labels, handles
def plot_line_by_product(dataframe, products, column, SSP, differentiator, title, RCP, nonBaselineScenario):
"""
Plots a line grouped by product
:param dataframe: the data being plotted
:param products: the list of products in the data being plotted
:param column: the column by which the products can be differentiated
:param SSP: the SSPs being plotted
:param differentiator: a secondary column to differentiate the products
:param title: the title of the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
# get plot information
axs, cmap, fig, im, ncol, normalizer, nrow = create_subplots(
dataframe=dataframe,
inner_loop_set=SSP,
products=products,
year=c.GCAMConstants.biochar_x,
SSP=SSP,
product_column=column,
title=title)
# find the number of model versions
# get color scheme based on number of model versions
versions = dataframe[differentiator].unique()
colors, num_colors = get_colors(len(versions))
counter = 0
try:
for k in versions:
color_counter = 0
for i in products:
y = dataframe[(dataframe[column] == i) & (dataframe[differentiator] == k)]
if not y.empty:
# plot all versions in y
color = colors[color_counter]
# get line of data to plot and plot it
lower = y.values.tolist()[0][c.GCAMConstants.skip_years:c.GCAMConstants.skip_years + len(
c.GCAMConstants.biochar_x)]
y_to_plot = y.values.tolist()[1][c.GCAMConstants.skip_years:c.GCAMConstants.skip_years + len(
c.GCAMConstants.biochar_x)] # only take the x values
upper = y.values.tolist()[2][c.GCAMConstants.skip_years:c.GCAMConstants.skip_years + len(
c.GCAMConstants.biochar_x)]
plot_line_on_axs(c.GCAMConstants.biochar_x, y_to_plot, str(i), color, axs, nrow, ncol, counter)
axs.fill_between(c.GCAMConstants.biochar_x, lower, upper, color=color, alpha = 0.2)
# get units
units = y['Units'].unique()[0]
l, h = finalize_line_subplot(axs, units, str(k), ncol, nrow, counter)
color_counter = color_counter + 1
counter = counter + 1
finalize_line_plot(fig, h, l, axs, nrow, ncol, counter, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def get_colors(num_versions):
"""
gets a color mapping based on the number of versions of the product
:param num_versions: the number of unique entries for each product
:return: a list containing the requisite colors, the number of colors for each product
"""
if num_versions == 1:
num_sub_colors = 1
return ["#BFBE43", "#74A751", "#698FC6", "#DD9452", "#C16861", "#A577A8", "#72B1B4", "#DCC060", "#AD9077",
"#9299A9"], num_sub_colors
elif num_versions == 2:
cmap = matplotlib.colormaps.get_cmap('tab20')
num_sub_colors = 2
elif num_versions == 4:
cmap = matplotlib.colormaps.get_cmap('tab20b')
num_sub_colors = 4
else:
return ["#1F78C8", "#ff0000", "#33a02c", "#6A33C2", "#ff7f00", "#565656",
"#FFD700", "#a6cee3", "#FB6496", "#b2df8a", "#CAB2D6", "#FDBF6F",
"#999999", "#EEE685", "#C8308C", "#FF83FA", "#C814FA", "#0000FF",
"#36648B", "#00E2E5", "#00FF00", "#778B00", "#BEBE00", "#8B3B00",
"#A52A3C"], 25
return [matplotlib.colors.rgb2hex(c) for c in cmap.colors], num_sub_colors
def plot_stacked_bar_product(df, year, SSP, column, title, RCP, nonBaselineScenario):
"""
Plots a stacked bar graph
:param df: dataframe
:param year: list of year to be plotted
:param SSP: list of SSPs to be plotted
:param column: column in the df to be plotted
:param title: title for the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
try:
# get subplot information
nrow, ncol = get_subplot_dimensions([year])
fig, axs = plt.subplots(nrow, ncol, sharex='all', sharey='all', gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
colors, num_colors = get_colors(1)
# format table
plot_df = df[df[['SSP']].isin(SSP).any(axis=1)]
if not isinstance(year, list):
plot_df = plot_df.loc[:, [year, 'SSP', 'GCAM', column]]
plot_df = plot_df.pivot(index='GCAM', columns=column, values=year)
plot_df = plot_df.loc[:, (plot_df != 0).any(axis=0)]
# add a column to df for sorting, then remove it
plot_df["sum"] = plot_df.abs().sum(axis=1)
plot_df = plot_df.sort_values(by="sum", ascending=False)
plot_df = plot_df.drop(['sum'], axis=1)
# plot stacked bar chart
plot_df.plot(kind="bar", stacked=True, color=colors, ax=axs)
else:
plot_df = pd.melt(plot_df, id_vars=['LandLeaf'], value_vars=[str(j) for j in year])
plot_df = plot_df.pivot(index="variable", columns="LandLeaf", values="value")
# plot stacked bar chart
plot_df.plot(kind="bar", stacked=True, color=colors, ax=axs)
# format plot
axs.set_title(title)
axs.set_ylabel(df["Units"].unique()[0])
plt.legend(bbox_to_anchor=(1, 1))
plt.subplots_adjust(bottom=0.5, right=.7, left=.15)
plt.xticks(rotation=60, ha='right')
ymin, ymax = axs.get_ylim()
axs.set_ylim(-ymax, ymax)
if title == "global land use change by year":
plt.gcf().set_size_inches(7, 8)
else:
plt.gcf().set_size_inches(12, 8)
plt.savefig("data/data_analysis/images/" + str(RCP) + "/" + title + ".png", dpi=300)
plt.show()
except ValueError as e:
print(e)
def plot_regional_vertical(dataframe, year, SSPs, y_label, title, x_column, y_column, x_label, RCP, nonBaselineScenario):
"""
Plots regional data in a categorical scatterplot
:param dataframe: data being plotted
:param year: year of y_axis data
:param SSPs: SSPs being evaluated
:param y_label: ylabel for graph
:param x_label: x-label for graph
:param title: title of graph
:param x_column: column used on the x-axis (formerly "GCAM")
:param y_column: column used on the y-axis (formerly "columnn")
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
# get colors
colors, divisions = get_colors(len(dataframe[y_column].unique()))
# plot for each SSP
for i in SSPs:
dataframe = dataframe[dataframe['SSP'].str.contains(i)]
for idx, item in enumerate(dataframe[y_column].unique()):
df = dataframe.loc[dataframe[y_column] == str(item)]
# scatter points
plt.scatter(x=df[x_column], y=df[str(year)], color=colors[idx], label=str(item))
# plot averages
# plt.axhline(y=df[str(year)].mean(), color=colors[idx], linestyle='dashed', label=str(item) + " average")
# finalize plot
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.xticks(rotation=60, ha='right')
plt.title(title)
plt.legend(bbox_to_anchor=(1, 1))
plt.subplots_adjust(bottom=0.4, right=.7)
plt.show()
plt.savefig("data/data_analysis/images/" + str(RCP) + "/" + title + ".png", dpi=300)
def plot_regional_vertical_avg(prices, year, SSPs, y_label, title, column, supply, RCP, nonBaselineScenario):
"""
Plots regional data in a categorical scatterplot
:param prices: price data being plotted
:param year: evaluation column
:param SSPs: SSPs being evaluated
:param y_label: ylabel for graph
:param title: title of graph
:param column: column used to identify unique categories
:param supply: supply data being plotted for weighted averages
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
# get colors
colors, divisions = get_colors(5)
# plot for each SSP
printing_str = ""
for i in SSPs:
dataframe = prices[prices['SSP'].str.contains(i)]
for idx, item in enumerate(dataframe[column].unique()):
df_price = dataframe.loc[dataframe[column] == str(item)]
# scatter points
global_avg = df_price[df_price[['GCAM']].isin(["Global"]).any(axis=1)]
df_price = df_price[~df_price[['GCAM']].isin(["Global"]).any(axis=1)]
df_lower = df_price[df_price["Version"] == "Lower CI"]
df_upper = df_price[df_price["Version"] == "Upper CI"]
df_median = df_price[df_price["Version"] == "Median"]
global_avg = global_avg[global_avg["Version"] == "Median"]
plt.scatter(x=df_median["GCAM"], y=df_median[str(year)], edgecolors=colors[idx], facecolors='none', label=str(item))
plt.scatter(x=df_lower["GCAM"], y=df_lower[str(year)], color=colors[idx], marker="*")
plt.scatter(x=df_upper["GCAM"], y=df_upper[str(year)], color=colors[idx], marker="x")
# finalize plot
plt.ylabel(y_label)
plt.xlabel("Region")
plt.xticks(rotation=60, ha='right')
plt.title(title)
plt.legend(bbox_to_anchor=(1, 1))
plt.subplots_adjust(bottom=0.5, right=.7, left=.15)
plt.gcf().set_size_inches(12, 8)
plt.savefig("data/data_analysis/images/" + str(RCP) + "/" + title + ".png", dpi=300)
plt.show()
def plot_line_product_CI(dataframe, products, column, SSP_baseline, differentiator, title, RCP, nonBaselineScenario):
"""
Plots a line grouped by product
:param dataframe: the data being plotted
:param products: the list of products in the data being plotted
:param column: the column by which the products can be differentiated
:param SSP_baseline: the SSPs being plotted
:param differentiator: a secondary column to differentiate the products
:param title: the title of the plot
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
if dataframe.empty: # if the datafame is empty, nothing can be plotted
print("empty dataframe")
return
# get plot information
# get subplot size
nrow, ncol = get_subplot_dimensions(["plot", "sidebar"])
# make plots and color scheme
fig, axs = plt.subplots(ncol, nrow, sharey='all', gridspec_kw={'wspace': 0.02, 'hspace': 0.2}, width_ratios=[12, 1])
# find the number of model versions
# get color scheme based on number of model versions
versions = dataframe[differentiator].unique()
colors, num_colors = get_colors(len(versions))
try:
color_counter = 0
for i in products:
if "SSP" in SSP_baseline:
y = dataframe[(dataframe[column] == i) & (dataframe['SSP'] == SSP_baseline)]
skip_years = c.GCAMConstants.skip_years
else:
y = dataframe[(dataframe[column] == i) & (dataframe['Version'] == SSP_baseline)]
skip_years = c.GCAMConstants.skip_years + 1
if not y.empty:
# plot all versions in y
color = colors[color_counter]
# get line of data to plot and plot it
y_to_plot = y.values.tolist()[0][skip_years:skip_years + len(
c.GCAMConstants.biochar_x)] # only take the x values
plot_line_on_axs(c.GCAMConstants.biochar_x, y_to_plot, str(i), color, axs, nrow, ncol, 0)
# get min and max data across SSPs
CI_df = dataframe[(dataframe[column] == i)]
min_seq = [CI_df[str(i)].min() for i in c.GCAMConstants.biochar_x]
max_seq = [CI_df[str(i)].max() for i in c.GCAMConstants.biochar_x]
# plot the min and max data
axs[0].fill_between(c.GCAMConstants.biochar_x, y1=min_seq, y2=max_seq, alpha=0.15, color=color)
# add rectangles on right plot
bar_year = str(max(c.GCAMConstants.biochar_x))
rect = patches.Rectangle((color_counter * 0.2, CI_df[bar_year].min()),
0.15, CI_df[bar_year].max() - CI_df[bar_year].min(), facecolor=color)
# Add the patch to the Axes
axs[1].add_patch(rect)
color_counter = color_counter + 1
# get units
units = dataframe['Units'].unique()[0]
l, h = finalize_line_subplot(axs, units, title, ncol, nrow, 0)
axs[1].axis('off')
finalize_line_plot(fig, h, l, axs, nrow, ncol, 2, title, RCP, nonBaselineScenario)
except ValueError as e:
print(e)
def plot_regional_rose(dataframe, year, SSPs, y_label, title, column, RCP, nonBaselineScenario):
"""
Plots regional data in a categorical scatterplot
:param dataframe: data being plotted
:param year: evaluation column
:param SSPs: SSPs being evaluated
:param y_label: ylabel for graph
:param title: title of graph
:param column: column used to identify unique categories
:param RCP: the RCP pathway on which the scenarios are evaluated
:param nonBaselineScenario: the set of scenarios in the sensitivity analysis being evaluated
:return: N/A
"""
# plot for each SSP
for i in SSPs:
dataframe = dataframe[dataframe['SSP'].str.contains(i)]
for idx, item in enumerate(dataframe[column].unique()):
df = dataframe.loc[dataframe[column] == str(item)]
# set figure size
fig = plt.figure()
ax = plt.subplot(111, polar=True)
ax.set_rlabel_position(0)
ax.spines["polar"].set_color('#ffffff')
# ax.set_title(str(item))
ax.grid(color="#d5d5d5", linestyle="dashed")