In [1]:
import urllib.request
import json
import codecs
import pandas as pd
import seaborn as sns
import matplotlib
%matplotlib inline
matplotlib.rcParams["figure.dpi"] = 240

Total number of buildings with housings according to number of properties. Data from the 2011 Census of Buildings.

Read more about the data source here.

In [2]:
def get_open_data_bcn(resource_id):
    "Fetches data from Barcelona's City Hall Open Data Service"
    reader = codecs.getreader("utf-8")
    url = 'http://opendata-ajuntament.barcelona.cat/data/api/action/datastore_search?resource_id=%s' % resource_id
    response = urllib.request.urlopen(url)
    return json.load(reader(response))
In [3]:
resource_id = "a6c01067-63eb-4532-a40a-39d80b7f8bb7"
data = get_open_data_bcn(resource_id)
In [4]:
barrios = pd.DataFrame(data["result"]["records"])
barrios.set_index("Barris", inplace=True)
barrios.drop(["Dte","_id"], axis=1, inplace=True)
sorted_cols = ['UnImmoble', 'DosImmobles', 'TresImmobles','QuatraImmobles', 
               'DeCincANou', 'DeDeuADinou', 'DeVintAVintINou', 'DeTrentaATrentaNou',
                'QuarantaIMes', 'Total']
barrios = barrios[sorted_cols]
new_cols = ["1", "2", "3", "4", "5-9", "10-19", "20-29", "30-39", "40+", "Total"]
barrios.columns = new_cols
barrios = barrios.applymap(lambda cell: cell.replace(".","")).applymap(lambda x: float(x) if x else 0)

How many properties per building does each Barcelona neighborhood have, in percent?

In [27]:
matplotlib.pyplot.figure(figsize=(7,16))
normed = (barrios.drop(["Total"],axis=1).T / barrios["Total"]).T
ax = sns.heatmap(100*normed, annot=True, linewidths=.5, cbar=False)
ax.xaxis.tick_top()