JavaScript from https://github.com/riatelab/statsbreaks/blob/main/src/method-headtail.js Port in Python of the same library
We borrowed sample data from https://observablehq.com/@ateliercartographie/head-tail-breaks
curl -s 'https://ec.europa.eu/eurostat/api/dissemination/statistics/1.0/data/demo_r_d3dens?format=json&lang=en&time=2019' >| raw_pop_nuts3.json
wget https://gisco-services.ec.europa.eu/distribution/v2/nuts/geojson/NUTS_RG_10M_2021_3035_LEVL_3.geojson
jq .dimension.geo.category.index raw_pop_nuts3.json # map_nuts3
jq .value raw_pop_nuts3.json # map_pop
import json
with open('raw_pop_nuts3.json') as infile:
raw_pop_nuts3 = json.load(infile)
map_nuts3 = raw_pop_nuts3.get('dimension').get('geo').get('category').get('index')
map_pop = {int(k):v for k,v in raw_pop_nuts3.get('value').items()}
with open('NUTS_RG_10M_2021_3035_LEVL_3.geojson') as infile:
NUTS_RG_10M_2021_3035_LEVL_3 = json.load(infile)
# map_pop.get(map_nuts3.get(ID))
pop_nuts3 = [map_pop.get(map_nuts3.get(d.get('properties').get('NUTS_ID'))) for d in NUTS_RG_10M_2021_3035_LEVL_3.get('features')]
for feature in NUTS_RG_10M_2021_3035_LEVL_3['features']:
feature['properties']['POP'] = map_pop.get(map_nuts3.get(d.get('properties').get('NUTS_ID')))
with open('NUTS_RG_10M_2021_3035_LEVL_3_WITH_POP.geojson', 'w') as infile:
json.dump(NUTS_RG_10M_2021_3035_LEVL_3, infile)
# map_pop.get(map_nuts3.get(ID))
# pop_nuts3 = [map_pop.get(map_nuts3.get(d.get('properties').get('NUTS_ID')) for d in NUTS_RG_10M_2021_3035_LEVL_3.get('features')]
# jq '.[0]' geojson_nuts3.json >| NUTS_RG_10M_2021_3035.geojson
# jq '.[0]' geojson_nuts3.json >| country_borders.geojson
# jq '.[2]' geojson_nuts3.json >| outline.geojson
Open in QGIS the file demo.qgs.qgz
Open the file generate-head-tail-style.py
in Python Console and run it.
Initialy we wanted to make a class based on QgsClassificationMethod to integrate the method in list of existing graduated styles like jenks
from qgis.core import QgsClassificationMethod
class QgsClassificationHeadTail(QgsClassificationMethod):
def name(self):
return 'Head Tail method'
# Below code throw an error "TypeError: qgis._core.QgsClassificationMethod cannot be instantiated or sub-classed"
# QgsClassificationMethod is an abstract class in C wrapped with sipify in Python. Do not know how to bypass the issue
QgsClassificationHeadTail()