I've created a incidence map for a city, but now i need to manipulate the legend ( decrease its size, put it bellow the map/graph, insert labels). i've used a json file to plot the territory. Here's my code:
Treatment by epidemiological week
filtro_semana = dados['Epidemiological Week'] >= 1
# to select the week of confirmed cases, manually enter here
df_weekofinterest = dados[filtro_semana]
cases_by_neighborhood = df_weekofinterest.groupby('Neighborhood').size().reset_index(name='Cases')
bairros = bairros.rename(columns={'NOME': 'Neighborhood'})
final_map_data = neighborhoods.merge(cases_by_neighborhood, on='Neighborhood', how='left')
final_map_data['Cases'] = final_map_data['Cases'].fillna(0).astype(int)
final_map_data = pd.merge(final_map_data, population_data, on='Neighborhood', how='left')
Now let's calculate the incidence of cases per 100,000 inhabitants
final_map_data['Incidence_per_100k'] = (final_map_data['Cases'] / final_map_data['population']) * 100000
Defines the size of the plot
fig, ax = plt.subplots(figsize=(10, 10))
Plots all neighborhoods based on the 'Cases' column
final_map_data.plot(column='Incidence_per_100k', cmap='Reds', linewidth=0.8, edgecolor='black',legend=True, ax=ax)
Plots the entire area of the neighborhood "Arquipélago" with a blue color and transparency
polygons_arquipelago = final_map_data[final_map_data['Neighborhood'] == "Arquipélago"]['geometry']
for polygon in polygons_arquipelago:
ax.add_patch(plt.Polygon(polygon.exterior, color='blue', alpha=0.5))
Adds neighborhood names
texts = []
labeled_neighborhoods = set()
for x, y, label in zip(final_map_data.geometry.centroid.x, final_map_data.geometry.centroid.y, final_map_data['Neighborhood']):
if label == "Arquipélago":
# Adjusts the position of the label for the "Arquipélago" neighborhood
arquipelago_polygon = final_map_data[final_map_data['Neighborhood'] == "Arquipélago"]['geometry'].iloc[0]
if not arquipelago_polygon.is_empty:
x, y = arquipelago_polygon.centroid.x, arquipelago_polygon.centroid.y
if label not in labeled_neighborhoods:
texts.append(ax.text(x, y, label, fontsize=4, ha='center', va='center'))
labeled_neighborhoods.add(label)
Automatically adjusts the position of the labels to avoid overlaps
adjust_text(texts, arrowprops=None)
Defines the plot limits
ax.set_xlim(final_map_data.total_bounds[0], final_map_data.total_bounds[2])
ax.set_ylim(final_map_data.total_bounds[1], final_map_data.total_bounds[3])
Additional settings
ax.set_axis_off()
plt.title('DENGUE INCIDENCE IN OFFICIAL NEIGHBORHOODS OF PORTO ALEGRE')
I've tryied to manipulate the legend with Matplotlib but it's not working, it stays the same.
Inserting Legend
if ax.get_legend():
ax.get_legend().set_title('Number of Cases')
ax.get_legend().set_bbox_to_anchor((1, 0.5)) # Legend position
ax.get_legend().set_frame_on(False) # Remove legend frame
ax.get_legend().get_texts()[0].set_fontsize(8) # Font size of values in legend
ax.get_legend().set_title('Number of Cases', fontsize=10) # Legend title