1

I am trying to make a choropleth with this data (source links in code). The below does produce one, but it's hard to really get anything meaningful from it without knowing which area is which.

I have tried making an interactive choropleth with the second block of code. All this does is break my laptop - it just freezes, I guess some kind of memory issue (tried folium too and can't align my coords to theirs). The only alternative I could think of was to try and add coloured dots and a legend with the 'local authority name' column, but I have no idea how to do that. I also tried just adding labels with the initials of the area, but they are far too big for the granularity of the areas and the whole plot disappears under them.

Is there a way to neatly attach the local authority information to my plot? Thanks for any suggestions! :)

import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from mpl_toolkits.axes_grid1 import make_axes_locatable
import folium
import plotly.express as px
import pyproj
plt.style.use('ggplot')
import json

#source: https://www.ons.gov.uk/peoplepopulationandcommunity/personalandhouseholdfinances/incomeandwealth/datasets/householdsinpovertyestimatesformiddlelayersuperoutputareasinenglandandwales
populationData=pd.read_csv("householdsinpoverty2014.csv")
#source: https://geoportal.statistics.gov.uk/datasets/ons::msoa-dec-2021-boundaries-full-extent-bfe-ew/explore
mapData= gpd.read_file("MSOA.shp")

mapData.drop(columns=['Shape__Are', 'Shape__Len','GlobalID','OBJECTID'],inplace=True)



populationData.drop(columns=['Unnamed: 9'],inplace=True)
populationData2=populationData.iloc[3:].copy()
populationData2.columns=populationData2.iloc[0]
populationDataClean=populationData2.iloc[1:].copy()

populationDataClean.reset_index(inplace=True)

populationDataClean.dropna(inplace=True)

populationDataClean.drop(columns=['MSOA name', 'Local authority code','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Lower Limit','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Upper Limit'],inplace=True)

populationDataClean.sort_values(by=['Percentage of Households Below 60% of the Median Income; (after housing costs)'],inplace=True)

populationDataClean['PercentBelowMedIncome']=populationDataClean['Percentage of Households Below 60% of the Median Income; (after housing costs)'].astype(float)

mapStats=mapData.merge(populationDataClean[populationDataClean['Region name']=='London'],left_on='MSOA21CD',right_on='MSOA code') #Zoom into London: [populationDataClean['Region name']=='London']

fig, ax = plt.subplots(1, figsize=(8, 8))
plt.xticks(rotation=90)
#divider = make_axes_locatable(ax)

#cax = divider.append_axes("right", size="5%", pad=0.1)
mapStats.plot(column="PercentBelowMedIncome", cmap="Blues", linewidth=0.4, ax=ax, edgecolor=".4",scheme='equalinterval',missing_kwds={
    "color": "lightgrey",
    "edgecolor": "red",
   "hatch": "///",
   "label": "Missing values",
   })
ax.set_title('% of Households Below 60% \n of the Median Income (London)', fontdict={'fontsize': '25', 'fontweight' : '3'})
ax.axis("off")
sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=6.7, vmax=50))
# empty array for the data range
sm._A = []
# add the colorbar to the figure
cbar = fig.colorbar(sm)
from plotly import graph_objects as go
fig = go.Figure(
go.Choroplethmapbox(
geojson=json,
featureidkey="properties.MSOA21CD",
locations=mapStats["MSOA21CD"], # <=== not areaCode
z=mapStats['PercentBelowMedIncome'],
zauto=True,
colorscale='Reds',
showscale=True
)
)
[ ]: fig.update_layout(mapbox_style='carto-positron',
mapbox_zoom=5,
mapbox_center_lon=-2.057852,
mapbox_center_lat=53.404854,
height=700,
width=700)
fig.show()

1 Answer 1

0

I have a couple of issues with your visualisation: firstly, the number of data in the shapefile you are using is very large. This causes the freezing. Secondly, the geographic coordinate system of this shapefile is not one that can be used in Poltly and needs to be converted. To annotate the name of the municipality, which is the ultimate goal, we need to get a free API key for mapbox. I have restricted your shapefile and data to London to solve this problem.Latitude and longitude for annotations are also needed, as one example, a central point in London has been added as text. I believe some mapbox styles overlay the region name as a layer, so that would be an object to consider.

import pandas as pd
import geopandas as gpd

populationData = pd.read_csv('./householdsinpovertyahcfye14.csv', skiprows=4)
mapData = gpd.read_file('./MSOA_(Dec_2021)/MSOA_(Dec_2021)_Boundaries_Full_Extent_(BFE)_EW.shp')
mapData.drop(columns=['Shape__Are', 'Shape__Len','GlobalID','OBJECTID'],inplace=True)
London_cities = ["City of London","City of Westminster","Kensington and Chelsea",
                 "Hammersmith and Fulham","Wandsworth","Lambeth","Southwark",
                 "Tower Hamlets","Hackney","Islington","Camden","Brent","Ealing",
                 "Hounslow","Richmond upon Thames","Kingston upon Thames",
                 "Merton","Sutton","Croydon","Bromley","Lewisham","Greenwich",
                 "Bexley","Havering","Barking and Dagenham","Redbridge","Newham",
                 "Waltham Forest","Haringey","Enfield","Barnet","Harrow","Hillingdon"]

mapData = mapData[mapData['MSOA21NM'].str.contains('|'.join(London_cities))]
mapData = mapData.to_crs(4326)

populationData.drop(columns=['Unnamed: 9'],inplace=True)
populationData2 = populationData.iloc[3:].copy()
#populationData2.columns=populationData2.iloc[0]
populationDataClean=populationData2.iloc[1:].copy()
populationDataClean.reset_index(inplace=True)
populationDataClean.dropna(inplace=True)
populationDataClean.drop(columns=['MSOA name', 'Local authority code','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Lower Limit','Percentage of Households Below 60% of the Median Income; (after housing costs); 95% Confidence Interval Upper Limit'],inplace=True)
populationDataClean.sort_values(by=['Percentage of Households Below 60% of the Median Income; (after housing costs)'],inplace=True)
populationDataClean['PercentBelowMedIncome']=populationDataClean['Percentage of Households Below 60% of the Median Income; (after housing costs)'].astype(float)

import plotly.graph_objects as go

token = open("./mapbox_api_key.txt").read()

fig = go.Figure(go.Choroplethmapbox(geojson=mapData.__geo_interface__,
                                    featureidkey="properties.MSOA21CD",
                                    locations=populationDataClean["MSOA code"], 
                                    z=populationDataClean["PercentBelowMedIncome"],
                                    zauto=True,
                                    text=populationDataClean["Local authority name"],
                                    colorscale='Reds',
                                    showscale=True)
               )
fig.add_trace(go.Scattermapbox(mode='markers+text',
                               lon=[-0.1277],
                               lat=[51.5073],
                               marker=dict(size=25, color='green'),
                               text='The Center of LONDON',
                               textposition='bottom right',
                               textfont=dict(color='green', size=18)
                           )
             )

fig.update_layout(
    mapbox_accesstoken=token,
    mapbox_style='basic',
    mapbox_zoom=9,
    mapbox_center_lon=-0.1277,
    mapbox_center_lat=51.5073,
    height=600,
)

fig.show()

enter image description here

enter image description here

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.