Plotting the expenses MPs have claimed on their constituencies
Published
2024-04-26
In my project trying to visualize the UK’s prisons, I hit a snag where plotly wouldn’t plot my whole dataset, so I need to make my own solution. I’ve also been looking into the carbon footprint of MPs’ expenses, so I have a readily available dataset to plot on a map of the UK to get a feel for how this could be done.
First, I need a map of the UK. There are maps available from the ONS, but these use the WGS84 standard for their co-ordinates, which doesn’t play nicely with D3, which I’m using here. Luckily, Martin Chorley has made topojson maps of each of the UK nations available here.
D3 likes geojson for its plots. You can get the features equivalent to geojson out of a topojson using topojson.feature().
The structure of a geojson object is a key type, which should be "FeatureCollection", and then an array of the features. For convenience, I’ve combined the features from the individual nations into one object.
I’m using the 2022-2023 expenses dataset I’ve used before.
Code
data =awaitFileAttachment("data/individualBusinessCosts_22_23.csv").csv({typed:true});
Then for each constituency, we can add up the amount paid for each category. The dataset is not perfectly clean; the constituency names are a bit inconsistent. I’ve manually corrected a few1, but a lot of the constituencies have ” CC” or ” BC” at the end. This isn’t on the map, so I’ve removed the suffix.
Then I define a couple of functions for getting this data into the visualisation. The first, get_amount, retrieves the expenses for a constituency if you supply the name. If there isn’t a matching value in the data, it returns undefined. This is the way the visualisation expects to fetch data2. The second function, to_pounds formats a number as pounds. This is a nice d3 function, and you can first define your locale so you use the right currency format.
So this isn’t a perfect set of visualisations. The constituency names for Northern Ireland aren’t on the map, so these only show grey, for example. It’s a good bit of practice for me though, and you can find some interesting patterns. For example, if you select the travel categories, there’s a general trend for increased spend the further the MP is from Westminster, which is to be expected. But why is the MP for Morecambe and Lunesdale (in north west England), spending twice as much as the MP for Moray (north east Scotland)? Why is the MP for Lincoln spending so much on staffing3?
I had originally used d3’s built-in group function which returns an object with nice behaviour for this, but the way I did it meant the expenses were summed up again every time you changed the visualisation. I’m sure there’s an elegant d3 solution, but mine works fine.↩︎