简体   繁体   中英

color a Choropleth map with the right colors #Python

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
import folium
import geojson

data= pd.read_csv('dans-ma-rue.csv', delimiter=';')
data=data.replace(to_replace='Mobiliers urbains dégradés (arrachés, cassés, tordus, bancals, en panne... )', value='Mobiliers urbains dégradés')

importing the map and getting the geo_json file:

macarte = folium.Map(location=[48.86,2.35], zoom_start=12.5,)
ARDT = r'arrondissements.geojson'

Here is the link of the geo Json file : https://data.opendatasoft.com/explore/dataset/arrondissements@parisdata/?flg=fr

# calculating total number of incidents per district
data2 = pd.DataFrame(data['ARRONDISSEMENT'])
data2 = pd.DataFrame(data2['ARRONDISSEMENT'].value_counts().astype(float))
data2.to_json('crimeagg.json')
data2 = data2.reset_index()
data2.columns = ['ARRONDISSEMENT', 'Nombre']
data2['ARRONDISSEMENT']=data2['ARRONDISSEMENT'].astype(int)
data2['ARRONDISSEMENT2']=data2['ARRONDISSEMENT'].apply(lambda x : str(x)+"ème Ardt")

Then creating the map :

macarte.choropleth(geo_data = ARDT,
    data = data2,
    columns = ['ARRONDISSEMENT','Nombre'],
    key_on = 'feature.properties.ARDT',
    fill_color = 'YlOrRd',
    fill_opacity = 0.7,
    line_opacity = 0.2,
    legend_name = 'Number of incidents per district')

display(macarte)

The code gives me a map with all districts but all with the same color. Thanks you very much !

Dimitri

I think the key_on parameter is set wrongly. It should match what you have in the geojson file. There is no ARDT attribute inside properties . You should use the attribute c_ar for uniquely identify the district ("arrondissment").

macarte.choropleth(geo_data = ARDT,
    data = data2,
    columns = ['ARRONDISSEMENT','Nombre'],
    key_on = 'feature.properties.c_ar',
    fill_color = 'YlOrRd',
    fill_opacity = 0.7,
    line_opacity = 0.2,
    legend_name = 'Number of incidents per district')

I had the same problem as you and this jupyter notebook helped me.

Note: According to this the choropleth function is old and will be deprecated and that GeoJson should be use instead. For me, both of them worked in the end.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM