-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotting_functions.py
815 lines (708 loc) · 23.3 KB
/
plotting_functions.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# PLOTTING FUNCTIONS
# =============================================================================
#%% Imports
import numpy as np
import pandas as pd
import geopandas as gpd
import matplotlib
import matplotlib.pyplot as plt
import datetime
import tikzplotlib # To save plots as TikZ pictures
from matplotlib.colors import ListedColormap
from matplotlib.ticker import MaxNLocator
from data_analysis import ser_global, vna_global
#%% Files
counties = gpd.read_feather('./data/IrishCountiesSimplified.feather')
bg = gpd.read_feather('./data/IrelandCoastline.feather') # Outline of Ireland
dublin_outline = counties[counties.index=='DUBLIN']
con_outlines = gpd.read_feather('./data/IrishConstituencies.feather')
#%% Palette
# Colour palette for plots
palette = [
'#F89E79', # 1. Carlow-Kilkenny
'#FBBC9E', # 2. Cavan-Monaghan
'#EAE856', # 3. Clare
'#F18E94', # 4. Cork East
'#FFD88A', # 5. Cork North-Central
'#95D6D7', # 6. Cork North-West
'#FACFE2', # 7. Cork South-Central
'#CFDF6A', # 8. Cork South-West
'#F287B7', # 9. Donegal
'#D293C1', # 10. Dublin Bay North
'#ECF794', # 11. Dublin Bay South
'#B5B0D8', # 12. Dublin Central
'#86D1D8', # 13. Dublin Fingal
'#63C2A0', # 14. Dublin Mid-West
'#FFEB94', # 15. Dublin North-West
'#F287B7', # 16. Dublin Rathdown
'#D0E28A', # 17. Dublin South-Central
'#F9C0C2', # 18. Dublin South-West
'#9FCF78', # 19. Dublin West
'#8FB7E1', # 20. Dún Laoghaire
'#F598A4', # 21. Galway East
'#FDC896', # 22. Galway West
'#F7AEBE', # 23. Kerry
'#D293C1', # 24. Kildare North
'#EFBED9', # 25. Kildare South
'#94CC7D', # 26. Laois-Offaly
'#F89E79', # 27. Limerick City
'#67C18C', # 28. Limerick County
'#FFEB94', # 29. Longford-Westmeath
'#63C2A0', # 30. Louth
'#A2DCED', # 31. Mayo
'#F7A6AD', # 32. Meath East
'#9FDBED', # 33. Meath West
'#44BEAA', # 34. Roscommon-Galway
'#E4EB9E', # 35. Sligo-Leitrim
'#B5B0D8', # 36. Tipperary
'#E4EB9E', # 37. Waterford
'#6ABACF', # 38. Wexford
'#FFE96B', # 39. Wicklow
]
cons = ['CARLOW-KILKENNY', 'CAVAN-MONAGHAN', 'CLARE', 'CORK EAST',
'CORK NORTH-CENTRAL', 'CORK NORTH-WEST', 'CORK SOUTH-CENTRAL',
'CORK SOUTH-WEST', 'DONEGAL', 'DUBLIN BAY NORTH',
'DUBLIN BAY SOUTH', 'DUBLIN CENTRAL', 'DUBLIN FINGAL',
'DUBLIN MID-WEST', 'DUBLIN NORTH-WEST', 'DUBLIN RATHDOWN',
'DUBLIN SOUTH-CENTRAL', 'DUBLIN SOUTH-WEST', 'DUBLIN WEST',
'DÚN LAOGHAIRE', 'GALWAY EAST', 'GALWAY WEST', 'KERRY',
'KILDARE NORTH', 'KILDARE SOUTH', 'LAOIS-OFFALY', 'LIMERICK CITY',
'LIMERICK COUNTY', 'LONGFORD-WESTMEATH', 'LOUTH', 'MAYO',
'MEATH EAST', 'MEATH WEST', 'ROSCOMMON-GALWAY', 'SLIGO-LEITRIM',
'TIPPERARY', 'WATERFORD', 'WEXFORD', 'WICKLOW']
color_dict = {con:color for con, color in zip(cons, palette)}
palette_dublin = palette[9:20]
plt.rcParams['figure.dpi'] = 300
#%%
def create_proxy(label):
'''
Create a proxy image to display custom labels in legend.
Used in make_full_plot for numeric legend.
'''
# For one-digit numbers, marker size should be smaller
ms = 1.9 if int(label) < 10 else 3
line = matplotlib.lines.Line2D(
[0],
[0],
linestyle='none',
mfc='black',
mec='none',
marker=r'$\mathregular{{{}}}$'.format(label),
markersize=ms
)
return line
#%%
def numbered_con_dict(df):
'''
Returns dictionary with constituency:number pairs,
in alphabetical order.
'''
cons = np.unique(df['CON'].str.title())
con_dict = {cons[i]:i+1 for i in range(len(cons))}
return con_dict
#%%
def tikzplotlib_fix_ncols(obj):
'''
Workaround for matplotlib 3.6 renamed legend's _ncol to _ncols,
which breaks tikzplotlib.
'''
if hasattr(obj, "_ncols"):
obj._ncol = obj._ncols
for child in obj.get_children():
tikzplotlib_fix_ncols(child)
#%% SER Table
def make_ser_and_vna_table(df, name='table', dpi=300, save_tex=False,
seats=False, use_current_seats=False):
'''
Creates a table showing the SER and VNA of each CON.
If use_current_seats=True, then use currently assigned seat numbers
to compute VNA.
If seats=True, add a column showing seats assigned to each CON.
'''
ser_dictionary = ser_global(df)
vna_dictionary = vna_global(df, use_current_seats)
fig, ax = plt.subplots()
# Hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
# Get SER data
table_data = pd.DataFrame.from_dict([ser_dictionary]).T
table_data = table_data.reset_index()
table_data.columns = ['Constituency','SER']
table_data['VNA'] = table_data['Constituency'].map(vna_dictionary)
table_data['Constituency'] = table_data['Constituency'].str.title()
table_data = table_data.round(3)
table_data['SER'] = table_data['SER'].apply('{:0<5}'.format)
table_data['VNA'] = table_data['VNA'].apply('{:0<5}'.format)
if seats:
if use_current_seats:
# Get current seat numbers from dataframe
table_data['Seats'] = list(df.groupby('CON').first()['SEATS'])
else:
# Compute seat number by rounding SER
table_data['Seats'] = np.round(table_data['SER']
.apply(float)).apply(int)
table_data = table_data[['Constituency', 'Seats', 'SER', 'VNA']]
col_widths =[0.4,0.2,0.2,0.2]
else:
col_widths =[0.4,0.2,0.2]
if save_tex:
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
# Save data to TeX
table_data.to_latex(f'./tex/{name}_{time}.tex', index=False)
t = ax.table(
cellText=table_data.values,
colLabels=table_data.columns,
loc='center',
colWidths=col_widths,
cellLoc='left'
)
t.scale(1, 2)
t.set_fontsize(15)
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
fig.savefig(
f'./images/{name}_{time}.png',
dpi=dpi,
bbox_inches='tight'
)
#%% SER Chart
def format_chart_data(df1, df2, metric='SER',
use_current_seats_for_current=True):
'''
Returns a dataframe indexed by constituency, with columns corresponding
to SER/VNA of the original and optimal configurations.
'''
if metric == 'SER':
# Create dictionaries of SER values for each CON
dictionary_1 = ser_global(df1)
dictionary_2 = ser_global(df2)
elif metric == 'VNA':
# Create dictionaries of VNA values for each CON
dictionary_1 = vna_global(df1, use_current_seats_for_current)
dictionary_2 = vna_global(df2)
# Create dataframes from dictionaries
data_1 = pd.DataFrame.from_dict([dictionary_1])
data_2 = pd.DataFrame.from_dict([dictionary_2])
# Concatenate dataframes, reset index, and transpose
data = pd.concat([data_1, data_2]).reset_index(drop=True).T
data.index = data.index.set_names('Constituency')
data.index = pd.Series(data.index.values).str.title()
# Label datasets
data = data.rename({0:'Original',1:'Optimal'}, axis=1)
# Round to three decimal places
data = data.round(3).abs()
data['Original'] = data['Original'].apply(
'{:0<5}'.format).astype('float64')
data['Optimal'] = data['Optimal'].apply(
'{:0<5}'.format).astype('float64')
return data
#%%
def make_chart(df1, df2, name='chart', dpi=300, x=15, y=11, filetype='png',
save_tex=False, metric='SER',
use_current_seats_for_current=True):
'''
Creates a bar chart comparing the SER/VNA of each CON for two states.
Saves a PNG by default, otherwise PDF.
'''
# Get formatted chart data
data = format_chart_data(df1, df2, metric, use_current_seats_for_current)
fig, ax = plt.subplots(1, 1, figsize=(x,y))
if metric=='SER':
# Plot horizontal lines at integer values
ax.hlines(
[1,2,3,4,5],
xmin=0,
xmax=50,
colors='darkgrey',
zorder=0
)
elif metric=='VNA':
ax.hlines(
[0.05],
xmin=0,
xmax=50,
colors='darkgrey',
zorder=0
)
# Plot bar chart
data.plot.bar(
rot=0,
ax=ax,
zorder=1,
alpha=0.9,
color=['powderblue', 'steelblue']
)
# Label axes
ax.set_xlabel('Constituency', fontsize=15)
ax.set_ylabel(metric, fontsize=15)
if metric == 'SER':
# Restrict y axis
ax.set_ylim(2,6)
# Only plot tick labels at integer values
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
# Plot vertical bar labels on the x axis
plt.setp(
ax.get_xticklabels(),
fontsize=12,
rotation='vertical'
)
# Set legend font size
font = matplotlib.font_manager.FontProperties(
style='normal',
size=16
)
ax.legend(prop=font)
if save_tex:
fig = plt.gcf()
tikzplotlib_fix_ncols(fig) # Fix naming issue in tikzplotlib
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
tikzplotlib.save(f'./tex/{name}_{metric}_{time}.tex')
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
if filetype.upper().strip() == 'PNG':
fig.savefig(
f'./images/{metric}_{name}_{time}.png',
dpi=dpi,
bbox_inches='tight'
)
elif filetype.upper().strip() == 'PDF':
fig.savefig(
f'./images/{metric}_{name}_{time}.pdf',
bbox_inches='tight',
transparent=True,
pad_inches=0
)
else:
fig.savefig(f'./images/{name}_{time}.{filetype.strip()}')
#%% SER Chart
def make_double_chart(df1, df2, name='double_chart', dpi=300, x=15, y=20,
filetype='png', save_tex=False,
use_current_seats_for_current=True):
'''
Creates a bar chart comparing the SER/VNA of each CON for two states.
Saves a PNG by default, otherwise PDF.
'''
# Get formatted chart data
ser_data = format_chart_data(
df1,
df2,
metric='SER'
)
vna_data = format_chart_data(
df1,
df2,
metric='VNA',
use_current_seats_for_current=use_current_seats_for_current
)
fig, axs = plt.subplots(2, 1, figsize=(x,y))
# Horizontal lines at integers for SER chart
axs[0].hlines(
[1,2,3,4,5],
xmin=0,
xmax=50,
colors='darkgrey',
zorder=0
)
# Horizontal line at threshold value of 0.05 for VNA chart
axs[1].hlines(
[0.05],
xmin=0,
xmax=50,
colors='darkgrey',
zorder=0
)
# Plot SER bar chart
ser_data.plot.bar(
rot=0,
ax=axs[0],
zorder=1,
alpha=0.9,
color=['powderblue', 'steelblue']
)
# Plot VNA bar chart
vna_data.plot.bar(
rot=0,
ax=axs[1],
zorder=2,
alpha=0.9,
color=['powderblue', 'steelblue'],
legend=False
)
# Label axes
for i in range(2):
# Plot vertical bar labels on x axes of both plots
plt.setp(
axs[i].get_xticklabels(),
fontsize=12,
rotation='vertical'
)
# Other settings for SER chart
axs[0].set_ylabel('SER', fontsize=15)
# Restrict y axis
axs[0].set_ylim(2,6)
# Only plot tick labels at integer values
axs[0].yaxis.set_major_locator(MaxNLocator(integer=True))
# Set legend font
font = matplotlib.font_manager.FontProperties(
style='normal',
size=16
)
axs[0].legend(prop=font)
# Other settings for VNA chart
axs[1].set_xlabel('Constituency', fontsize=15)
axs[1].set_ylabel('VNA', fontsize=15)
plt.tight_layout()
if save_tex:
fig = plt.gcf()
tikzplotlib_fix_ncols(fig) # Fix naming issue in tikzplotlib
tikzplotlib.clean_figure()
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
tikzplotlib.save(f'./tex/comp_chart_{time}.tex')
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
if filetype.upper().strip() == 'PNG':
fig.savefig(
f'./images/{name}_{time}.png',
dpi=dpi,
bbox_inches='tight'
)
elif filetype.upper().strip == 'PDF':
fig.savefig(
f'./images/{name}_{time}.pdf',
bbox_inches='tight',
transparent=True,
pad_inches=0
)
else:
fig.savefig(f'./images/{name}_{time}.{filetype.strip()}')
#%% Plot
def make_plot(df_orig, name='plot', dpi=500, legend=True, x=11, y=11,
filetype='png', numbered=False, save=True, ax=None,
outline_dublin=False, highlight_changes=False, use_cons=False):
'''
Creates a plot of EDs coloured according to CON.
If save=True, then saves a PNG/PDF depending on filetype.
If save=False, ax can be passed for plotting.
If highlight_changes=True, then changed EDs are highlighted.
'''
if ax == None:
# If not plotting on an existing axis, then create a new figure
fig, ax = plt.subplots(1, 1, figsize=(x,y))
fontsize = 10
markerscale = 4
else:
fontsize = 3
markerscale = 2
df = df_orig.copy()
df['CON'] = df['CON'].str.title()
if highlight_changes:
con_outlines.plot(
facecolor='grey',
edgecolor='darkgrey',
ax=ax
)
changed = df[df['CHANGE']>0]
changed['CON'] = changed['CON'].str.upper()
changed['COLOR'] = changed['CON'].map(color_dict)
changed.plot(color=changed['COLOR'], ax=ax)
legend=False
elif use_cons:
con_outlines['CON'] = con_outlines['CON'].str.title()
con_outlines['geometry'] = con_outlines['geometry'].simplify(15)
con_outlines.plot(
column='CON',
cmap=ListedColormap(palette),
ax=ax,
categorical=True,
legend=legend
)
else:
# Plot EDs coloured according to CON
df.plot(
column='CON',
cmap=ListedColormap(palette),
ax=ax,
categorical=True,
legend=legend
)
# Remove axes and tick labels
ax.set_axis_off()
if numbered:
cons = np.unique(df[df['COUNTY']!='DUBLIN']['CON'])
nums = numbered_con_dict(df)
for c in cons:
# Get centroid of each constituency
pt_xy = gpd.GeoSeries(df[df['CON']==c].unary_union.centroid)
pt = (pt_xy.x, pt_xy.y)
# Annotate with number at centroid
ax.annotate(
text=nums[c],
xy=pt,
ha='center',
fontsize=fontsize,
bbox={'boxstyle':'circle','color':'white'}
)
if save:
labels = [nums[c] for c in cons]
proxies = [create_proxy(num) for num in labels]
ax.legend(proxies, cons, numpoints=1, markerscale=markerscale)
if outline_dublin:
dublin_outline.plot(
ax=ax,
facecolor='none',
edgecolor='grey',
linewidth=0.5
)
if legend:
leg = ax.get_legend()
leg.set_bbox_to_anchor((0.85, 0.5, 0.5, 0.5))
if save:
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
if filetype.upper().strip() == 'PNG':
fig.savefig(
f'./images/{name}_{time}.png',
dpi=dpi,
bbox_inches='tight',
transparent=True
)
elif filetype.upper().strip() == 'PDF':
fig.savefig(
f'./images/{name}_{time}.pdf',
bbox_inches='tight',
transparent=True,
pad_inches=0
)
else:
fig.savefig(f'./images/{name}_{time}.{filetype.strip()}')
#%% Dublin Plot
def make_dublin_plot(df_orig, name='dublin_plot', dpi=500, legend=True,
x=11, y=11, filetype='png', numbered=False, save=True,
ax=None, use_cons=False):
'''
Creates a plot of EDs coloured according to CON.
Saves a PNG by default, otherwise PDF.
'''
if ax == None:
# If not plotting on an existing axis, then create a new figure
fig, ax = plt.subplots(1, 1, figsize=(x,y))
fontsize = 10
markerscale = 4
else:
fontsize = 3
markerscale = 2
df = df_orig.copy()
df['CON'] = df['CON'].str.title()
dub = df[df['COUNTY']=='DUBLIN']
if use_cons:
dub_cons = con_outlines[con_outlines['COUNTY']=='DUBLIN'].copy()
dub_cons['CON'] = dub_cons['CON'].str.title()
dub_cons['geometry'] = dub_cons['geometry'].simplify(15)
dub_cons.plot(
column='CON',
cmap=ListedColormap(palette_dublin),
ax=ax,
categorical=True,
legend=legend
)
else:
# Plot EDs coloured according to CON
dub.plot(
column='CON',
cmap=ListedColormap(palette_dublin),
ax=ax,
categorical=True,
legend=legend
)
# Remove axes
ax.set_axis_off()
if numbered:
cons = np.unique(dub['CON'])
nums = numbered_con_dict(df)
for c in cons:
# Get centroid of each constituency
pt_xy = gpd.GeoSeries(df[df['CON']==c].unary_union.centroid)
pt = (pt_xy.x, pt_xy.y)
# Annotate with number at centroid
ax.annotate(
text=nums[c],
xy=pt,
ha='center',
fontsize=fontsize,
bbox={'boxstyle':'circle','color':'white'}
)
if save:
labels = [nums[c] for c in cons]
proxies = [create_proxy(num) for num in labels]
ax.legend(proxies, cons, numpoints=1, markerscale=markerscale)
if legend:
leg = ax.get_legend()
leg.set_bbox_to_anchor((0.85, 0.5, 0.5, 0.5))
if save:
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
if filetype.upper().strip() == 'PNG':
fig.savefig(
f'./images/{name}_{time}.png',
dpi=dpi,
bbox_inches='tight',
transparent=True
)
elif filetype.upper().strip() == 'PDF':
fig.savefig(
f'./images/{name}_{time}.pdf',
bbox_inches='tight',
transparent=True,
pad_inches=0
)
else:
fig.savefig(f'./images/{name}_{time}.{filetype.strip()}')
#%%
def make_legend(df_orig, ax):
'''
Creates a numbered legend for the 39 constituencies.
'''
ax.set_aspect(2)
ax.margins(0,0)
# Remove axes
ax.set_axis_off()
df = df_orig.copy()
df['CON'] = df['CON'].str.title()
# Constituencies
cons = np.unique(df['CON'])
# Constituency-number dictionary
nums = numbered_con_dict(df)
# Numbers corresponding to constituencies
labels = [nums[c] for c in cons]
# Create legend images showing numbers
proxies = [create_proxy(num) for num in labels]
# Plot legend
ax.legend(
proxies,
cons,
numpoints=1,
markerscale=1,
fontsize=3,
loc='upper right',
bbox_to_anchor=(1,0.97),
borderpad=0.8
)
# Set width of legend frame
leg = ax.get_legend()
leg.get_frame().set_linewidth(0.2)
#%%
def make_full_plot(df, save=True, use_cons=True):
'''
Make a numbered plot showing all Irish constituencies,
including a zoomed view of Dublin.
Use use_cons=True if plotting current configuration, as this eliminates
ED edge lines from antialiasing.
'''
# A = Full country plot
# B = Zoomed view of Dublin
# C = Custom numbered legend
mosaic_layout = '''
AAAC
AAAC
AAAC
BBBC
BBBC
'''
fig, axs = plt.subplot_mosaic(mosaic_layout)
plt.subplots_adjust(wspace=-0.91, hspace=0)
# Plot A
make_plot(
df,
legend=False,
numbered=True,
save=False,
ax=axs['A'],
outline_dublin=True,
use_cons=use_cons
)
# Plot B
make_dublin_plot(
df,
legend=False,
numbered=True,
save=False,
ax=axs['B'],
use_cons=use_cons
)
# Plot C
make_legend(
df,
ax=axs['C']
)
plt.margins(0,0)
if save:
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
fig.savefig(f'./images/full_plot_{time}.png',
dpi=500,
bbox_inches='tight',
transparent=True,
pad_inches=0.1
)
#%% County Boundary Plot
def make_county_boundary_plot(df_orig, name='plot', dpi=500, x=11, y=11,
filetype='png'):
'''
Creates a plot of EDs coloured according to CON, overlaid with county
boundaries.
Saves a PNG by default, otherwise PDF.
'''
fig, ax = plt.subplots(1,1,figsize=(x,y))
df = df_orig.copy()
df['CON'] = df['CON'].str.title()
# Plot background colour
bg.plot(
facecolor='none',
edgecolor='grey',
ax=ax,
linewidth=2
)
# Plot EDs coloured according to CON
df.plot(
column='CON',
cmap=ListedColormap(palette),
ax=ax,
categorical=True,
legend=True
)
# Plot county boundaries on top
counties.plot(
facecolor='none',
edgecolor='grey',
ax=ax
)
leg = ax.get_legend()
leg.set_bbox_to_anchor((0.9, 0.5, 0.5, 0.5))
# Remove axes
ax.set_axis_off()
# Get current time
time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
if filetype.upper().strip() == 'PNG':
fig.savefig(
f'./images/{name}_county_boundary_{time}.png',
dpi=dpi,
bbox_inches='tight',
transparent=True
)
elif filetype.upper().strip() == 'PDF':
fig.savefig(
f'./images/{name}_county_boundary_{time}.pdf',
bbox_inches='tight',
transparent=True,
pad_inches=0
)
else:
fig.savefig(f'./images/{name}_{time}.{filetype.strip()}')