-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_generator.py
94 lines (71 loc) · 3.59 KB
/
map_generator.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
import geopandas as gpd
from pathlib import Path
import argparse
class MapGenerator(object):
"""
Generates map of given district of kerala with localbody boundaries.
...
Attributes
----------
district : str
Name of district of which map is needed.
out_format : str default : png
Format of image output. Normal formats supported by matplotlib `savefig()`.
Methods
-------
plot_map(cmap = True)
Function to save the plotin given image format.
"""
def __init__(self, district: str, out_format: str = 'png'):
self.district = district.lower()
self.out_format = out_format.lower()
def __clean_map(self) -> gpd.geodataframe.GeoDataFrame:
df = gpd.read_file(f"geojson_files/{self.district}.geojson")
remove_words = ['panchayath', 'Grama', 'grama', 'Panchayath', 'panchayat',
'Panchayat','Gramapanchayat', 'Gramapanchayath','Grampanchayat']
rem = r'\b(?:{})\b'.format('|'.join(remove_words))
df["NAME"] = df['name'].str.replace(rem, '',regex=True)
df.dropna(subset=['NAME'], inplace=True)
v_df = df[df['local_authority:IN'].isin(['municipal_corporation','gram_panchayat','municipality'])].copy()
v_df["NAME"] = v_df["NAME"].str.rstrip()
v_df['coords'] = v_df['geometry'].apply(lambda x: x.representative_point().coords[:])
v_df['coords'] = [coords[0] for coords in v_df['coords']]
return v_df
def plot_map(self,cmap: bool = True):
"""
Saves image of map of given district with option for colour or balck and white map with given format.
Parameters
----------
cmap : bool, default : True
If coloured map is needed, use `cmap = True`. Else for black and white map diagram, use `cmap = False`.
"""
v_df = self.__clean_map()
if cmap == True:
ax = v_df.plot(figsize=(25,25),scheme="quantiles", edgecolor='gray',linewidth=2,cmap= 'Set3')
else:
ax = v_df.plot(figsize=(25,25),scheme="quantiles", edgecolor='black',linewidth=2,color='white')
ax.tick_params(left = False, bottom = False, labelbottom = False, labelleft = False)
ax.axis('off')
for idx, row in v_df.iterrows():
ax.annotate(text=row['NAME'], xy=row['coords'],color='black',
horizontalalignment='center')
fig = ax.get_figure()
fig.tight_layout()
Path('maps').mkdir(parents=True, exist_ok=True)
fig.savefig(f"maps/{self.district.capitalize()}.{self.out_format}",dpi=300,
bbox_inches='tight',pad_inches = 0)
print(f"Map of {self.district.capitalize()} created in maps folder.")
if __name__=='__main__':
parser = argparse.ArgumentParser("Generates map of given district of kerala with localbody boundaries.")
parser.add_argument("-d", "--district", required=True, type = str, help= 'District name')
parser.add_argument("-f", "--format", required=False, type = str, help= 'Output image format (default: png)')
parser.add_argument("-c", "--cmap", required=False, type = bool, help= 'If coloured map is required, use True. else use False.(default : True)')
args = parser.parse_args()
if args.format == True:
maps = MapGenerator(args.district, args.format)
else:
maps = MapGenerator(args.district)
if args.cmap == True:
maps.plot_map(cmap= args.cmap)
else:
maps.plot_map()