-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_map_update.py
More file actions
157 lines (114 loc) · 5.79 KB
/
plot_map_update.py
File metadata and controls
157 lines (114 loc) · 5.79 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
import geopandas as gpd
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import math
import matplotlib.colors as colors
from geopandas import GeoDataFrame
from shapely.geometry import Point
import numpy as np
matplotlib.rcParams['svg.fonttype'] = 'none'
def get_closest_lower_year(my_list, year):
left, right = 0, len(my_list) - 1
closest_lower = None
while left <= right:
mid = (left + right) // 2
if my_list[mid] <= year:
closest_lower = my_list[mid]
left = mid + 1
else:
right = mid - 1
return closest_lower
def close_event():
plt.close() #timer calls this function after 3 seconds and closes the window
geotagged_path = "geotagged/geotagged_new_new.csv"
geotagged_df = pd.read_csv(geotagged_path)
plot_dict_dicts = {}
for i, row in geotagged_df.iterrows():
if not math.isnan(row['year']):
year = str(int(row['year']))
historic_name = row['historical_coutry_name']
weight = row['weight']
if year not in plot_dict_dicts:
plot_dict_dicts[year] = {}
plot_dict_dicts[year][historic_name] = plot_dict_dicts[year].get(historic_name, 0) + weight
# Create a DataFrame from the dictionary
weights_df = pd.DataFrame(plot_dict_dicts).fillna(0)
#weights_df.to_csv('weights_df.csv')
# Transpose the DataFrame to have countries as rows and years as columns
weights_df = weights_df.T
# Optionally, you can rename the index column (years) to 'Year'
weights_df.index.name = 'Year'
window_size = 5
weights_df_ma = weights_df.rolling(window=window_size, axis=0, min_periods=1).mean()
#weights_df_ma.to_csv('weights_ma.csv')
file_years = list(filter(lambda x: not math.isnan(x) ,geotagged_df['map_year'].unique()))
file_years = list(map(lambda x: str(int(x)),file_years))
# years = list(filter(lambda x: not math.isnan(x) ,geotagged_df['year'].unique()))
# years = list(map(lambda x: str(int(x)),years))
years = list(map(lambda x: str(int(x)), list(range(1960,2021))))
# Normalize the data for the colormap
vmin = 1
vmax = weights_df_ma.to_numpy().max()
# for year in geotagged_df['year'].unique():
# for hist_country in geotagged_df.loc[geotagged_df['year'] == year, 'historical_coutry_name' ].unique():
# vmax = max(vmax, geotagged_df.loc[(geotagged_df['year'] == year) & (geotagged_df['historical_coutry_name'] == hist_country), 'weight'].sum())
norm = colors.Normalize(vmin=vmin, vmax=vmax)
for idx,y in enumerate(years):
map_year = get_closest_lower_year(file_years, y)
folder_path = "C:/Users/Panuskova/Nextcloud/translation-mapping/historical-basemaps/geojson"
# Load the GeoJSON map
geojson_path = folder_path + '/world_' + str(map_year)+ '.geojson'
gdf = gpd.read_file(geojson_path)
gdf.set_index('NAME', inplace=True)
common_countries_columns = weights_df_ma[weights_df_ma.index == y].columns.intersection(gdf.index).sort_values().dropna()
# Create a DataFrame from the dictionary
data_df = pd.DataFrame(list(plot_dict_dicts[y].items()), columns=['country', 'weight'])
data_df.set_index('country', inplace=True)
gdf['weight'] = 0
# Set the weights for countries with available data
for country in common_countries_columns:
weight = weights_df_ma[country][weights_df_ma.index == y ].T.sort_index().values
# When the weight was below 1, it did not plot any colour
if weight > 0 :
weight +=3
if isinstance(gdf.loc[country, 'weight'], (int, float, np.int64, np.float64)):
gdf.loc[country, 'weight'] = weight
else:
gdf.loc[country, 'weight'] = [weight] * len(gdf.loc[country, 'weight'])
#gdf.loc[common_countries_columns, 'weight'] = weights_df_ma[common_countries_columns.to_list()][weights_df_ma.index == y ].T.sort_index().values
# Define the colormap for non-zero values
cmap = plt.cm.OrRd
# Create a new 'color' column in the GeoDataFrame and set it to white (neutral) for all countries
gdf['color'] = 'white'
# Set the color for countries with available data
# for country, weight in plot_dict_dicts[y].items():
# if weight > 0:
# color_rgb = cmap(norm(weight))[:3] # Get RGB values from the colormap
# gdf.loc[gdf.index == country, 'color'] = '#%02x%02x%02x' % tuple(int(c * 255) for c in color_rgb)
for country, row in gdf.iterrows() :
if row['weight'] > 0:
color_rgb = cmap(norm(row['weight']))[:3] # Get RGB values from the colormap
gdf.loc[gdf.index == country, 'color'] = '#%02x%02x%02x' % tuple(int(c * 255) for c in color_rgb)
geometry = [Point(xy) for xy in zip(geotagged_df.loc[geotagged_df['year'] == int(y),"geonames_lng"],geotagged_df.loc[geotagged_df['year'] == int(y),"geonames_lat"])]
crs = {'init': 'epsg:4326'}
caps_points = GeoDataFrame(geotagged_df.loc[geotagged_df['year'] == int(y),"geonames_name"], crs=crs, geometry=geometry)
# Plotting the choropleth map
fig, ax = plt.subplots(1, 1, figsize=(15, 10) ) #
# Timer
timer = fig.canvas.new_timer(interval = 3000) #creating a timer object and setting an interval of 3000 milliseconds
timer.add_callback(close_event)
ax.set_aspect('equal')
gdf.plot(facecolor=gdf['color'], edgecolor='0.8', linewidth=0.8, ax=ax, legend=True)
#gdf.plot(column='weight', cmap='OrRd', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)
# Plot cities
# caps_points.plot(ax = ax, marker = "p", markersize = 0.1, c = "red", )
# Write years in title
ax.set_title('Choropleth Map {}'.format(str(y)))
ax.set_axis_off() # Turn off the axis to remove the axis frame
cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
fig.colorbar(cbar)
plt.savefig('plots/individual years ma/'+ax.get_title() + '.png')
#timer.start()
#plt.show()
close_event()