I want to make a choropleth map of regions but shade it according to local population density. This is not the problem of masking a raster with a shapefile but to overlay two representations of data over the same area. One (population density) is as good as continuous for our purpose and could be rasterized in whichever object is necessary. The other data is coarse, at the level of subregions, and thus comes vectorized.

Colors (hues) could come from the choropleth (thus stay constant within subregions) but the transparency of each pixel should vary inversely with local population density, as approximated by a local average in a rastering call.

See the two independent plots below. Rasterio or the HoloViz family (GeoViz and Datashader) look relevant but I could not make them accomplish this.

The raster comes from Facebook's high-resolution maps of residence, here for Hungarian youth.

import dask.dataframe as dd
df = dd.read_csv("HUN_youth_15_24_2020-02-01.csv")
import datashader as ds
from datashader import transfer_functions as tf
from datashader.colors import Greys9
Greys9_r = list(reversed(Greys9))[:-2]
plot_width  = int(750)
plot_height = int(plot_width//1.2)
x_range, y_range =(16.141528,22.883194), (45.755139,48.582917)
cvs = ds.Canvas(plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=y_range)
agg = cvs.points(df, 'longitude', 'latitude',  ds.mean('population'))
img = tf.shade(agg,cmap=Greys9_r, how='log')

And this produces a choropleth map of the relevant subregions of Hungary (here with mock data), using the shapefile from GADM 3.6:

import pandas as pd
import geopandas as gpd
import xarray as xr
import numpy as np
import mkl_random
shp = gpd.read_file('gadm36_HUN_2.shp')
GID_2 = shp['GID_2']
values = mkl_random.uniform(0.5, 20, 168)
arr = xr.DataArray(values, dims='GID_2', coords={'GID_2':GID_2})
shp = shp.set_index('GID_2')
shp = shp.assign(myvar=arr.to_series())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.