A choropleth map created with Folium and Pandas. Pull data into a dataframe, bind to a feature of the GeoJSON, map it. Folium allows you to specify any of the color brewer sequential color groups, and also allows you to specify the d3 quantize scale range:
import folium
import json
import pandas as pd
import vincent
county_data = r'us_county_data.csv'
county_geo = r'us-counties.json'
#We want to map the county codes we have in our geometry to those in the
#county_data file, which contains additional rows we don't need
with open(county_geo, 'r') as f:
get_id = json.load(f)
county_codes = [x['id'] for x in get_id['features']]
county_df = pd.DataFrame({'FIPS_Code': county_codes}, dtype=str)
#Read into Dataframe, cast to string for consistency
df = pd.read_csv(county_data, na_values=[' '])
df['FIPS_Code'] = df['FIPS_Code'].astype(str)
#Perform an inner join, pad NA's with data from nearest county
merged = pd.merge(df, county_df, on='FIPS_Code', how='inner')
merged = merged.fillna(method='pad')
map = folium.Map(location=[39.8282, -98.5795], zoom_start=4)
map.geo_json(county_geo, data=merged,
columns=['FIPS_Code', 'Unemployed_2011'], key_on='feature.id',
fill_color='YlGnBu', line_opacity=0.3,
quantize_range=[0, 5000])
map.create_map()
xxxxxxxxxx
<head>
<link rel="stylesheet" href="https://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="https://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://d3js.org/queue.v1.min.js"></script>
<style>
#map {
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
}
</style>
</head>
<body>
<div id="map" style="width: 960px; height: 500px"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.5/leaflet.min.js"></script>
<script>
queue()
.defer(d3.json, 'data.json')
.defer(d3.json, 'us-counties.json')
.await(makeMap)
function makeMap(error, data_1,gjson_1) {
function matchKey(datapoint, key_variable){
return(parseFloat(key_variable[0][datapoint]));
};
var color = d3.scale.quantize()
.domain([0, 5000])
.range(['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0', '#225EA8', '#0C2C84']);
var map = L.map('map').setView([39.8282, -98.5795], 4);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
}).addTo(map);
function style_1(feature) {
return {
fillColor: color(matchKey(feature.id, data_1)),
weight: 1,
opacity: 0.3,
color: 'black',
fillOpacity: 0.6
};
}
gJson_layer_1 = L.geoJson(gjson_1, {style: style_1}).addTo(map)
};
</script>
</body>
Modified http://d3js.org/d3.v3.min.js to a secure url
Modified http://d3js.org/queue.v1.min.js to a secure url
Modified http://cdn.leafletjs.com/leaflet-0.5/leaflet.js to a secure url
https://d3js.org/d3.v3.min.js
https://d3js.org/queue.v1.min.js
https://cdn.leafletjs.com/leaflet-0.5/leaflet.js