Q004 - Dove si trova il laboratorio? Mappatura


In [34]:
# -*- coding: UTF-8 -*-

# Render our plots inline
%matplotlib inline 

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from matplotlib.collections import LineCollection
from matplotlib.patches import Polygon
from matplotlib.patches import Polygon
from mpl_toolkits.basemap import Basemap
import shapefile # pip install pyshp
import seaborn
import shutil

from geopy.geocoders import Nominatim
geolocator = Nominatim()

pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier, overridden by seaborn
pd.set_option('display.max_columns', None) # Display all the columns
plt.rcParams['font.family'] = 'sans-serif' # Sans Serif fonts for all the graphs

# Reference for color palettes: http://web.stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html

# Change the font
matplotlib.rcParams.update({'font.family': 'Source Sans Pro'})

# Reference for colormap gradients: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
# From http://nbviewer.ipython.org/github/rjtavares/numbers_arent_people/blob/master/experiments/Plotting%20with%20Basemap%20and%20Shapefiles.ipynb

In [2]:
# Load csv file first
data = pd.read_csv("data/lab-survey.csv", encoding="utf-8")

In [3]:
# Get the distribution of cities
data["D4[SQ001]"] = data["D4[SQ001]"].str.lower()
city = data["D4[SQ001]"].value_counts()

# Filter data manually for badly written input
#city = city.drop("milano/amsterdam")
#city.ix["milano"] += 1
#city.ix["amsterdam"] = 1
city = city.drop("alpignano (to)")
city.ix["alpignano"] = 1
city = city.drop("cascina (pi)")
city.ix["cascina"] = 1
city = city.drop("comunanza (ap)")
city.ix["comunanza"] = 1
city = city.drop("cinquefrondi rc")
city.ix["cinquefrondi"] = 1
city = city.drop("maniago (pn)")
city.ix["maniago"] = 1
city = city.drop("bagnacavallo (ra)")
city.ix["bagnacavallo"] = 1
city = city.drop("cesena + rimini ")
city.ix["cesena"] = 1

print "Data:"
print city


Data:
milano                 7
roma                   5
terni                  2
firenze                2
nuoro                  1
aosta                  1
pavia                  1
reggio emilia          1
trieste                1
alessandria            1
torino                 1
marsala                1
bologna                1
uggiano la chiesa      1
messina                1
ivrea                  1
genova                 1
venezia                1
borgomanero            1
parma                  1
fabriano               1
chieri                 1
sesto fiorentino       1
roma                   1
trento                 1
rimini                 1
padova                 1
isernia                1
tolentino              1
bucine                 1
settimo torinese       1
pesaro                 1
san dona di piave      1
bolzano                1
cenadi                 1
palermo                1
torino                 1
imperia                1
pula                   1
frosinone              1
faenza                 1
grassano               1
treviso                1
catania                1
rho                    1
tavagnacco             1
cavriglia              1
casalecchio di reno    1
verona                 1
tradate                1
sesto san giovanni     1
alpignano              1
cascina                1
comunanza              1
cinquefrondi           1
maniago                1
bagnacavallo           1
cesena                 1
Length: 58, dtype: int64

In [4]:
%%capture output

# Save the output as a variable that can be saved to a file
# Gather data
places = {}

from time import sleep

# Find region and province
for i in city.index:
    location = geolocator.geocode(i)
    dove = location.address
    places[i] = {}
    places[i]["x"] = location.longitude
    places[i]["y"] = location.latitude
    places[i]["size"] = city[i]
    print dove.encode('utf-8'), city[i]
    dove1 = [x.strip() for x in dove.split(',')]
    
    # Fix the Rome error
    if dove1[0] == "Roma":
        reg_code = "LAZ" 
        prov_code = "RM"
    else:
        reg_code = dove1[2] 
        prov_code = dove1[1]
        
    places[i]["reg"] = reg_code
    places[i]["prov"] = prov_code
    sleep(10)

In [5]:
# Save+show the output to a text file
%save Q004-MapOfLabsInItaly.py str(output)
shutil.move("Q004-MapOfLabsInItaly.py", "text/Q004-MapOfLabsInItaly.txt")


The following commands were written to file `Q004-MapOfLabsInItaly.py`:
Milano, MI, LOM, Italia 7
Roma, LAZ, Italia 5
Terni, TR, UMB, Italia 2
Firenze, FI, TOS, Italia 2
Nùgoro/Nuoro, NU, SAR, 08100, Italia 1
Aosta, AO, VDA, 11100, Italia 1
Pavia, PV, LOM, Italia 1
Reggio nell'Emilia, RE, EMR, Italia 1
Trieste, TS, FVG, Italia 1
Alessandria, AL, PIE, Italia 1
Torino, TO, PIE, Italia 1
Marsala, TP, SIC, Italia 1
Bologna, BO, EMR, Italia 1
Uggiano La Chiesa, LE, PUG, Italia 1
Messina, ME, SIC, Italia 1
Ivrea, TO, PIE, Italia 1
Genova, GE, LIG, Italia 1
Venezia, VE, VEN, Italia 1
Borgomanero, NO, PIE, Italia 1
Parma, PR, EMR, Italia 1
Fabriano, AN, MAR, Italia 1
Chieri, TO, PIE, Italia 1
Sesto Fiorentino, FI, TOS, Italia 1
Roma, LAZ, Italia 1
Trento, Agusan Del Sur, Caraga, Philippines 1
Rimini, RN, EMR, Italia 1
Padova, PD, VEN, Italia 1
Isernia, IS, MOL, Italia 1
Tolentino, MC, MAR, Italia 1
Bucine, AR, TOS, Italia 1
Settimo Torinese, TO, PIE, Italia 1
Pesaro, PU, MAR, Italia 1
San Donà di Piave, VE, VEN, Italia 1
Bolzano - Bozen, BZ, TAA, Italia 1
Cenadi, CZ, CAL, Italia 1
Palermo, PA, SIC, Italia 1
Torino, TO, PIE, Italia 1
Imperia, IM, LIG, Italia 1
Pula, Grad Pula, Istarska županija, 52100, Hrvatska 1
Frosinone, FR, LAZ, Italia 1
Faenza, RA, EMR, Italia 1
Grassano, MT, BAS, Italia 1
Treviso, TV, VEN, Italia 1
Catania, CT, SIC, Italia 1
Rho, MI, LOM, Italia 1
Tavagnacco, UD, FVG, Italia 1
Cavriglia, AR, TOS, Italia 1
Casalecchio di Reno, BO, EMR, Italia 1
Verona, VR, VEN, Italia 1
Tradate, VA, LOM, Italia 1
Sesto San Giovanni, MI, LOM, Italia 1
Alpignano, TO, PIE, Italia 1
Cascina, PI, TOS, Italia 1
Comunanza, AP, MAR, Italia 1
Cinquefrondi, RC, CAL, Italia 1
Maniago, PN, FVG, Italia 1
Bagnacavallo, RA, EMR, Italia 1
Cesena, FC, EMR, Italia 1

Mappatura a punti


In [6]:
figure(figsize=(15,15))

# Create the map: Europe
id_map0 = Basemap(llcrnrlon=-30, llcrnrlat=25, # lower left corner
                 urcrnrlon=40, urcrnrlat=80, # upper right corner
                 resolution="h") 

# Draw important features
id_map0.drawcoastlines(linewidth=.3) 
id_map0.drawcountries(linewidth=.2)
id_map0.fillcontinents(color='0.8') # Light gray
id_map0.drawmapboundary()

# Transform dict into lists
x = []
y = []
size = []
for i in places:
    x.append(places[i]["x"])
    y.append(places[i]["y"])
    size.append(places[i]["size"])

x1, y1 = id_map0(x,y)

# Normalized alpha from each node "size"
alpha = []
for i in size:
    normalized = (1-0.2)/(max(size)-min(size))*(i-max(size))+1
    alpha.append(normalized)

# Plot data
for i in range(len(x1)):
    id_map0.plot(x1[i], y1[i], 'or', markersize=7, alpha=alpha[i])

# Save the file
plt.title(u'Mappa dei FabLab/makerspace italiani', fontsize=18, y=1.02)
plt.savefig('svg/Q004-MapOfLabsInEurope-plot.svg')
plt.savefig('png/Q004-MapOfLabsInEurope-plot.png')
plt.savefig('pdf/Q004-MapOfLabsInEurope-plot.pdf')



In [7]:
figure(figsize=(15,15))

# Create the map: Italy
id_map1 = Basemap(projection="merc", llcrnrlat=35, urcrnrlat=48, 
            llcrnrlon=5, urcrnrlon=22, resolution="h")

# Draw important features
id_map1.drawcoastlines(linewidth=.3) 
id_map1.drawcountries(linewidth=.2)
id_map1.fillcontinents(color='0.8') # Light gray
id_map1.drawmapboundary()

# Transform dict into lists
x = []
y = []
size = []
for i in places:
    x.append(places[i]["x"])
    y.append(places[i]["y"])
    size.append(places[i]["size"])

x1, y1 = id_map1(x,y)
    
# Plot data
for i in range(len(x1)):
    id_map1.plot(x1[i], y1[i], 'or', markersize=size[i]*3, alpha=.5)

# Save the file
plt.title(u'Mappa dei FabLab/makerspace italiani', fontsize=18, y=1.02)
plt.savefig('svg/Q004-MapOfLabsInItaly-plot.svg')
plt.savefig('png/Q004-MapOfLabsInItaly-plot.png')
plt.savefig('pdf/Q004-MapOfLabsInItaly-plot.pdf')


Mappatura per Regioni


In [56]:
# Read regions shapefile
r = shapefile.Reader(r"borders/Reg2011_WGS84/r1")
shapes = r.shapes()
records = r.records()

# Read regions format, for manually fixing it later
for record in records:
    print record
    location = geolocator.geocode(record[2])
    dove = location.address
    print dove


[1, 1, 'Piemonte', 1333438.25859, 25387079830.7]
PIE, Italia
[2, 2, "Valle D'Aosta", 325838.760581, 3260902116.95]
AO, VDA, Italia
[3, 3, 'Lombardia', 1511143.07444, 23863449799.9]
LOM, Italia
[4, 4, 'Trentino-Alto Adige', 859879.277151, 13604915800.9]
TAA, Italia
[5, 5, 'Veneto', 1146942.96396, 18407272451.8]
VEN, Italia
[6, 6, 'Friuli Venezia Giulia', 770148.393089, 7862266855.52]
FVG, Italia
[7, 7, 'Liguria', 1080315.62764, 5416218657.32]
LIG, Italia
[8, 8, 'Emilia-Romagna', 1260958.54938, 22452552904.6]
EMR, Italia
[9, 9, 'Toscana', 1545218.22077, 22986947637.7]
TOS, Italia
[10, 10, 'Umbria', 671132.713736, 8464251163.15]
UMB, Italia
[11, 11, 'Marche', 711097.171728, 9401333626.95]
MAR, Italia
[12, 12, 'Lazio', 1201486.09377, 17232123330.3]
LAZ, Italia
[13, 13, 'Abruzzo', 664543.541309, 10831676349.0]
ABR, Italia
[14, 14, 'Molise', 471201.615164, 4460512062.58]
MOL, Italia
[15, 15, 'Campania', 1090762.87842, 13670835248.2]
CAM, Italia
[16, 16, 'Puglia', 1507355.36605, 19540853688.5]
PUG, Italia
[17, 17, 'Basilicata', 675756.873772, 10073287646.6]
BAS, Italia
[18, 18, 'Calabria', 934666.253851, 15221895218.9]
CAL, Italia
[19, 19, 'Sicilia', 1731345.85174, 25832399994.5]
SIC, Italia
[20, 20, 'Sardegna', 2128481.99326, 24100139070.1]
SAR, Italia

In [57]:
# Calculate values for each region

reg_values = {}

#print records[0],records[0][2]

# Store region values
for i in records:
    reg_values[i[2]] = 0

# Calculate region values
for j in places:
    region = places[j]["reg"]
    # Transform region code into region name
    if places[j]["reg"] == "PIE":
        region = "Piemonte"
    elif places[j]["reg"] == "VDA":
        region = "Valle D'Aosta"
    elif places[j]["reg"] == "LOM":
        region = "Lombardia"
    elif places[j]["reg"] == "TAA":
        region = "Trentino-Alto Adige"
    elif places[j]["reg"] == "VEN":
        region = "Veneto"
    elif places[j]["reg"] == "FVG":
        region = "Friuli Venezia Giulia"
    elif places[j]["reg"] == "LIG":
        region = "Liguria"
    elif places[j]["reg"] == "EMR":
        region = "Emilia-Romagna"
    elif places[j]["reg"] == "TOS":
        region = "Toscana"
    elif places[j]["reg"] == "UMB":
        region = "Umbria"
    elif places[j]["reg"] == "MAR":
        region = "Marche"
    elif places[j]["reg"] == "LAZ":
        region = "Lazio"
    elif places[j]["reg"] == "ABR":
        region = "Abruzzo"
    elif places[j]["reg"] == "MOL":
        region = "Molise"
    elif places[j]["reg"] == "CAM":
        region = "Campania"
    elif places[j]["reg"] == "PUG":
        region = "Puglia"
    elif places[j]["reg"] == "BAS":
        region = "Basilicata"
    elif places[j]["reg"] == "CAL":
        region = "Calabria"
    elif places[j]["reg"] == "SIC":
        region = "Sicilia"
    elif places[j]["reg"] == "SAR":
        region = "Sardegna"
    
    # Check if the region is in Italy
    if region not in reg_values:
        print "Not in Italy!"
    else:
        print region
        reg_values[region] += places[j]["size"]
    
# Assign values
for i,m in enumerate(records):
    m.append(reg_values[m[2]])


Emilia-Romagna
Umbria
Toscana
Piemonte
Friuli Venezia Giulia
Not in Italy!
Emilia-Romagna
Piemonte
Veneto
Calabria
Liguria
Marche
Puglia
Sardegna
Emilia-Romagna
Sicilia
Piemonte
Piemonte
Friuli Venezia Giulia
Emilia-Romagna
Lombardia
Valle D'Aosta
Marche
Lazio
Sicilia
Marche
Lombardia
Veneto
Emilia-Romagna
Emilia-Romagna
Toscana
Lombardia
Emilia-Romagna
Toscana
Friuli Venezia Giulia
Lombardia
Sicilia
Veneto
Basilicata
Emilia-Romagna
Lazio
Liguria
Veneto
Piemonte
Sicilia
Calabria
Trentino-Alto Adige
Veneto
Lombardia
Toscana
Piemonte
Toscana
Marche
Piemonte
Lazio
Molise
Piemonte
Not in Italy!

In [58]:
%%capture output
# Get value for each region
for i in records:
    print i[2],":",i[5]

In [59]:
# Save+show the output to a text file
%save Q004-LabRegioni.py str(output)
shutil.move("Q004-LabRegioni.py", "text/Q004-LabRegioni.txt")


The following commands were written to file `Q004-LabRegioni.py`:
Piemonte : 8
Valle D'Aosta : 1
Lombardia : 11
Trentino-Alto Adige : 1
Veneto : 5
Friuli Venezia Giulia : 3
Liguria : 2
Emilia-Romagna : 8
Toscana : 6
Umbria : 2
Marche : 4
Lazio : 7
Abruzzo : 0
Molise : 1
Campania : 0
Puglia : 1
Basilicata : 1
Calabria : 2
Sicilia : 4
Sardegna : 1


In [60]:
# Plot value for each region
value_dict = {}
for i in records:
    value_dict[i[2]] = i[5]

regionu = pd.Series(value_dict)
region = regionu.order()

In [61]:
# Plot the data
plt.figure(figsize=(16,6))
plt.xlabel(u'Regioni', fontsize=16)
plt.ylabel('Lab', fontsize=16)
plt.title(u"Dove si trova il laboratorio?", fontsize=18, y=1.02)
my_colors = seaborn.color_palette("husl", len(region)) # Set color palette
region.plot(kind="bar",color=my_colors)
plt.savefig(u"svg/Q004-LabRegioni.svg")
plt.savefig(u"png/Q004-LabRegioni.png")
plt.savefig(u"pdf/Q004-LabRegioni.pdf")



In [20]:
figure(figsize=(15,15))

ax = plt.subplot(111)

# Italy
m = Basemap(projection="merc", llcrnrlat=35, urcrnrlat=48, 
            llcrnrlon=5, urcrnrlon=22, resolution="h")

m.drawcoastlines()
m.drawmapboundary()
m.drawcountries()
m.fillcontinents(color = '#C0C0C0')

# Draw the shapefile
for record, shape in zip(records,shapes):
    lons,lats = zip(*shape.points)
    data = np.array(m(lons, lats)).T

    if len(shape.parts) == 1:
        segs = [data,]
    else:
        segs = []
        for i in range(1,len(shape.parts)):
            index = shape.parts[i-1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])

    lines = LineCollection(segs,antialiaseds=(1,))
    lines.set_facecolors(cm.PuBu(record[5]*30))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)
    
# Save the file
plt.title(u'Mappa dei FabLab/makerspace italiani', fontsize=18, y=1.02)
plt.savefig('svg/Q004-MapOfLabsInItaly-Regioni.svg')
plt.savefig('png/Q004-MapOfLabsInItaly-Regioni.png')
plt.savefig('pdf/Q004-MapOfLabsInItaly-Regioni.pdf')


Mappatura per Province


In [48]:
# Read province shapefile
r = shapefile.Reader(r"borders/Prov2011_WGS84/r1")
shapes = r.shapes()
records = r.records()

for record in records:
    print record, record[4]


[1, 1, 1, 'Torino', 'TO', 593394.131125, 6827010594.94] TO
[2, 1, 2, 'Vercelli', 'VC', 458757.847813, 2081632395.14] VC
[3, 1, 3, 'Novara', 'NO', 276724.330761, 1340269555.68] NO
[4, 1, 4, 'Cuneo', 'CN', 542068.161823, 6894934031.82] CN
[5, 1, 5, 'Asti', 'AT', 356523.761944, 1510193303.16] AT
[6, 1, 6, 'Alessandria', 'AL', 545446.862361, 3558838710.1] AL
[7, 2, 7, 'Aosta', 'AO', 325838.760581, 3260902116.95] AO
[8, 7, 8, 'Imperia', 'IM', 221993.150712, 1154778590.2] IM
[9, 7, 9, 'Savona', 'SV', 303898.070659, 1546289648.39] SV
[10, 7, 10, 'Genova', 'GE', 469920.955281, 1833775514.42] GE
[11, 7, 11, 'La Spezia', 'SP', 289353.574391, 881374904.304] SP
[12, 3, 12, 'Varese', 'VA', 277186.677796, 1198260409.08] VA
[13, 3, 13, 'Como', 'CO', 296560.260595, 1279037185.92] CO
[14, 3, 14, 'Sondrio', 'SO', 488652.832965, 3195728854.72] SO
[15, 3, 15, 'Milano', 'MI', 380895.852317, 1575511230.05] MI
[16, 3, 16, 'Bergamo', 'BG', 334771.144912, 2745937280.77] BG
[17, 3, 17, 'Brescia', 'BS', 488119.823611, 4785552826.88] BS
[18, 3, 18, 'Pavia', 'PV', 526365.8537, 2968629395.48] PV
[19, 3, 19, 'Cremona', 'CR', 413627.678916, 1770433081.26] CR
[20, 3, 20, 'Mantova', 'MN', 418187.94888, 2341388217.49] MN
[21, 4, 21, 'Bolzano', 'BZ', 664507.457935, 7397962023.95] BZ
[22, 4, 22, 'Trento', 'TN', 642832.734836, 6206953776.95] TN
[23, 5, 23, 'Verona', 'VR', 368177.490434, 3096325864.0] VR
[24, 5, 24, 'Vicenza', 'VI', 358303.44465, 2722489379.95] VI
[25, 5, 25, 'Belluno', 'BL', 446933.069784, 3672097478.88] BL
[26, 5, 26, 'Treviso', 'TV', 342158.777892, 2479831252.34] TV
[27, 5, 27, 'Venezia', 'VE', 505142.362386, 2473065892.48] VE
[28, 5, 28, 'Padova', 'PD', 365792.448275, 2144154103.96] PD
[29, 5, 29, 'Rovigo', 'RO', 340337.883077, 1819308480.16] RO
[30, 6, 30, 'Udine', 'UD', 537750.769511, 4907236212.87] UD
[31, 6, 31, 'Gorizia', 'GO', 208763.228395, 467138149.53] GO
[32, 6, 32, 'Trieste', 'TS', 147279.286835, 212506745.629] TS
[33, 8, 33, 'Piacenza', 'PC', 353038.308707, 2585804302.08] PC
[34, 8, 34, 'Parma', 'PR', 342803.492474, 3447452890.41] PR
[35, 8, 35, "Reggio nell'Emilia", 'RE', 282406.240349, 2291180052.89] RE
[36, 8, 36, 'Modena', 'MO', 357760.019581, 2687923716.79] MO
[37, 8, 37, 'Bologna', 'BO', 438115.509427, 3702306157.02] BO
[38, 8, 38, 'Ferrara', 'FE', 356801.023464, 2635081879.57] FE
[39, 8, 39, 'Ravenna', 'RA', 335600.443674, 1859420901.73] RA
[40, 8, 40, "Forli'-Cesena", 'FC', 285064.804009, 2378355062.1] FC
[41, 11, 41, 'Pesaro e Urbino', 'PU', 370916.094687, 2567754690.74] PU
[42, 11, 42, 'Ancona', 'AN', 319188.959311, 1963244389.84] AN
[43, 11, 43, 'Macerata', 'MC', 360296.238738, 2779359184.69] MC
[44, 11, 44, 'Ascoli Piceno', 'AP', 229378.528163, 1228208254.0] AP
[45, 9, 45, 'Massa Carrara', 'MS', 219086.199894, 1154619579.05] MS
[46, 9, 46, 'Lucca', 'LU', 229913.969298, 1773274473.08] LU
[47, 9, 47, 'Pistoia', 'PT', 185760.704223, 964178175.109] PT
[48, 9, 48, 'Firenze', 'FI', 462146.990119, 3513668089.28] FI
[49, 9, 49, 'Livorno', 'LI', 567203.447421, 1213473651.99] LI
[50, 9, 50, 'Pisa', 'PI', 367411.333142, 2444855638.14] PI
[51, 9, 51, 'Arezzo', 'AR', 406017.00165, 3233044070.29] AR
[52, 9, 52, 'Siena', 'SI', 429433.235285, 3820875919.1] SI
[53, 9, 53, 'Grosseto', 'GR', 535162.241494, 4503248562.13] GR
[54, 10, 54, 'Perugia', 'PG', 656871.427634, 6337094339.19] PG
[55, 10, 55, 'Terni', 'TR', 415660.649702, 2127156823.96] TR
[56, 12, 56, 'Viterbo', 'VT', 446981.525651, 3615223879.95] VT
[57, 12, 57, 'Rieti', 'RI', 408297.864964, 2750400330.53] RI
[58, 12, 58, 'Roma', 'RM', 697882.824172, 5363306572.42] RM
[59, 12, 59, 'Latina', 'LT', 498787.645509, 2256174445.51] LT
[60, 12, 60, 'Frosinone', 'FR', 359759.393286, 3247018101.84] FR
[61, 15, 61, 'Caserta', 'CE', 357982.19273, 2651320783.51] CE
[62, 15, 62, 'Benevento', 'BN', 330541.527748, 2080406079.26] BN
[63, 15, 63, 'Napoli', 'NA', 491267.797976, 1178955654.45] NA
[64, 15, 64, 'Avellino', 'AV', 401285.675358, 2806012724.09] AV
[65, 15, 65, 'Salerno', 'SA', 551676.995805, 4954140006.88] SA
[66, 13, 66, "L'Aquila", 'AQ', 496154.071054, 5047420082.55] AQ
[67, 13, 67, 'Teramo', 'TE', 236588.476076, 1954369365.59] TE
[68, 13, 68, 'Pescara', 'PE', 231482.926768, 1230309008.8] PE
[69, 13, 69, 'Chieti', 'CH', 289964.748721, 2599577892.1] CH
[70, 14, 70, 'Campobasso', 'CB', 324559.557398, 2925330404.75] CB
[71, 16, 71, 'Foggia', 'FG', 544526.954647, 7007449108.91] FG
[72, 16, 72, 'Bari', 'BA', 469915.551668, 3862794636.47] BA
[73, 16, 73, 'Taranto', 'TA', 419416.787824, 2467369484.5] TA
[74, 16, 74, 'Brindisi', 'BR', 323538.536903, 1861222128.87] BR
[75, 16, 75, 'Lecce', 'LE', 361261.523396, 2799066226.84] LE
[76, 17, 76, 'Potenza', 'PZ', 645360.72798, 6594390986.43] PZ
[77, 17, 77, 'Matera', 'MT', 401715.130819, 3478896660.13] MT
[78, 18, 78, 'Cosenza', 'CS', 589625.512861, 6709743492.14] CS
[79, 18, 79, 'Catanzaro', 'CZ', 360562.192377, 2415451245.92] CZ
[80, 18, 80, 'Reggio di Calabria', 'RC', 342695.656644, 3210373821.13] RC
[93, 6, 93, 'Pordenone', 'PN', 305616.747858, 2275385747.49] PN
[94, 14, 94, 'Isernia', 'IS', 279537.119074, 1535181657.83] IS
[96, 1, 96, 'Biella', 'BI', 171833.179749, 913281309.605] BI
[97, 3, 97, 'Lecco', 'LC', 203161.255805, 814579695.19] LC
[98, 3, 98, 'Lodi', 'LO', 272172.27826, 782977759.866] LO
[99, 8, 99, 'Rimini', 'RN', 288762.454762, 865027941.977] RN
[100, 9, 100, 'Prato', 'PO', 129342.24473, 365709479.491] PO
[101, 18, 101, 'Crotone', 'KR', 292647.354271, 1735684755.51] KR
[102, 18, 102, 'Vibo Valentia', 'VV', 235305.782349, 1150641904.19] VV
[103, 1, 103, 'Verbano-Cusio-Ossola', 'VB', 316524.068952, 2260919930.29] VB
[108, 3, 108, 'Monza e della Brianza', 'MB', 164692.672716, 405413863.152] MB
[109, 11, 109, 'Fermo', 'FM', 226570.052516, 862767107.687] FM
[110, 16, 110, 'Barletta-Andria-Trani', 'BT', 275816.509833, 1542952102.96] BT
[81, 19, 81, 'Trapani', 'TP', 528941.717732, 2469623453.1] TP
[82, 19, 82, 'Palermo', 'PA', 643605.781905, 5009281911.94] PA
[83, 19, 83, 'Messina', 'ME', 611747.029636, 3266129484.27] ME
[84, 19, 84, 'Agrigento', 'AG', 550663.87242, 3052590013.77] AG
[85, 19, 85, 'Caltanissetta', 'CL', 454473.176001, 2138369319.97] CL
[86, 19, 86, 'Enna', 'EN', 403944.476581, 2574704618.91] EN
[87, 19, 87, 'Catania', 'CT', 587128.083433, 3573682171.93] CT
[88, 19, 88, 'Ragusa', 'RG', 302539.22984, 1623885364.94] RG
[89, 19, 89, 'Siracusa', 'SR', 468092.865341, 2124133655.66] SR
[90, 20, 90, 'Sassari', 'SS', 664278.268295, 4286026884.2] SS
[91, 20, 91, 'Nuoro', 'NU', 486491.346782, 3931680916.73] NU
[92, 20, 92, 'Cagliari', 'CA', 623876.408561, 4570413298.56] CA
[95, 20, 95, 'Oristano', 'OR', 436227.247393, 3034246261.1] OR
[104, 20, 104, 'Olbia-Tempio', 'OT', 914396.378793, 3406180544.79] OT
[105, 20, 105, 'Ogliastra', 'OG', 263120.089279, 1854546752.77] OG
[106, 20, 106, 'Medio Campidano', 'VS', 261663.245975, 1517337234.12] VS
[107, 20, 107, 'Carbonia-Iglesias', 'CI', 372519.739031, 1499707177.8] CI

In [49]:
# Calculate values for each province

prov_values = {}

# Store province values
for i in records:
    prov_values[i[4]] = 0

# Calculate provice values
for j in places:
    if places[j]["prov"] in prov_values:
        prov_values[places[j]["prov"]] += places[j]["size"]
    
# Assign values
for i,m in enumerate(records):
    m.append(prov_values[m[4]])

In [50]:
%%capture output
# Get value for each region
for i in records:
    print i[3],":",i[7]

In [51]:
# Save+show the output to a text file
%save Q004-LabProvince.py str(output)
shutil.move("Q004-LabProvince.py", "text/Q004-LabProvince.txt")


The following commands were written to file `Q004-LabProvince.py`:
Torino : 6
Vercelli : 0
Novara : 1
Cuneo : 0
Asti : 0
Alessandria : 1
Aosta : 1
Imperia : 1
Savona : 0
Genova : 1
La Spezia : 0
Varese : 1
Como : 0
Sondrio : 0
Milano : 9
Bergamo : 0
Brescia : 0
Pavia : 1
Cremona : 0
Mantova : 0
Bolzano : 1
Trento : 0
Verona : 1
Vicenza : 0
Belluno : 0
Treviso : 1
Venezia : 2
Padova : 1
Rovigo : 0
Udine : 1
Gorizia : 0
Trieste : 1
Piacenza : 0
Parma : 1
Reggio nell'Emilia : 1
Modena : 0
Bologna : 2
Ferrara : 0
Ravenna : 2
Forli'-Cesena : 1
Pesaro e Urbino : 1
Ancona : 1
Macerata : 1
Ascoli Piceno : 1
Massa Carrara : 0
Lucca : 0
Pistoia : 0
Firenze : 3
Livorno : 0
Pisa : 1
Arezzo : 2
Siena : 0
Grosseto : 0
Perugia : 0
Terni : 2
Viterbo : 0
Rieti : 0
Roma : 6
Latina : 0
Frosinone : 1
Caserta : 0
Benevento : 0
Napoli : 0
Avellino : 0
Salerno : 0
L'Aquila : 0
Teramo : 0
Pescara : 0
Chieti : 0
Campobasso : 0
Foggia : 0
Bari : 0
Taranto : 0
Brindisi : 0
Lecce : 1
Potenza : 0
Matera : 1
Cosenza : 0
Catanzaro : 1
Reggio di Calabria : 1
Pordenone : 1
Isernia : 1
Biella : 0
Lecco : 0
Lodi : 0
Rimini : 1
Prato : 0
Crotone : 0
Vibo Valentia : 0
Verbano-Cusio-Ossola : 0
Monza e della Brianza : 0
Fermo : 0
Barletta-Andria-Trani : 0
Trapani : 1
Palermo : 1
Messina : 1
Agrigento : 0
Caltanissetta : 0
Enna : 0
Catania : 1
Ragusa : 0
Siracusa : 0
Sassari : 0
Nuoro : 1
Cagliari : 0
Oristano : 0
Olbia-Tempio : 0
Ogliastra : 0
Medio Campidano : 0
Carbonia-Iglesias : 0


In [52]:
# Plot value for each region
value_dict = {}
for i in records:
    value_dict[i[3]] = i[7]

provu = pd.Series(value_dict)
prov = provu.order()

In [55]:
# Plot the data
plt.figure(figsize=(16,6))
plt.xlabel(u'Province', fontsize=16)
plt.ylabel('Lab', fontsize=16)
plt.title(u"Dove si trova il laboratorio?", fontsize=18, y=1.02)
my_colors = seaborn.color_palette("husl", len(prov)) # Set color palette
prov.plot(kind="bar",color=my_colors)
plt.savefig(u"svg/Q004-LabProvince.svg")
plt.savefig(u"png/Q004-LabProvince.png")
plt.savefig(u"pdf/Q004-LabProvince.pdf")



In [27]:
figure(figsize=(15,15))

ax = plt.subplot(111)

# Italy
m = Basemap(projection="merc", llcrnrlat=35, urcrnrlat=48, 
            llcrnrlon=5, urcrnrlon=22, resolution="h")

m.drawcoastlines()
m.drawmapboundary()
m.drawcountries()
m.fillcontinents(color = '#C0C0C0')

for record, shape in zip(records,shapes):
    #read shape
    lons,lats = zip(*shape.points)
    data = np.array(m(lons, lats)).T

    #each shape may have different segments
    if len(shape.parts) == 1:
        segs = [data,]
    else:
        segs = []
        for i in range(1,len(shape.parts)):
            index = shape.parts[i-1]
            index2 = shape.parts[i]
            segs.append(data[index:index2])
        segs.append(data[index2:])

    #draws the segments, and sets its properties. A colormap is used to get the gradient effect.
    lines = LineCollection(segs,antialiaseds=(1,))
    lines.set_facecolors(cm.PuBu(record[7]*30))
    lines.set_edgecolors('k')
    lines.set_linewidth(0.1)
    ax.add_collection(lines)
    
# Save the file
plt.title(u'Mappa dei FabLab/makerspace italiani', fontsize=18, y=1.02)
plt.savefig('svg/Q004-MapOfLabsInItaly-Province.svg')
plt.savefig('png/Q004-MapOfLabsInItaly-Province.png')
plt.savefig('pdf/Q004-MapOfLabsInItaly-Province.pdf')


Mappa dell'Italia #02


In [29]:
figure(figsize=(15,15))

# Create the map: Italy
id_map1 = Basemap(projection="merc", llcrnrlat=35, urcrnrlat=48, 
            llcrnrlon=5, urcrnrlon=22, resolution="h")

# Draw important features
id_map1.drawcoastlines(linewidth=.3) 
id_map1.drawcountries(linewidth=.2)
id_map1.fillcontinents(color='0.8') # Light gray
id_map1.drawmapboundary()

# Transform dict into lists
x = []
y = []
size = []
for i in places:
    x.append(places[i]["x"])
    y.append(places[i]["y"])
    size.append(places[i]["size"])

x1, y1 = id_map1(x,y)
    
# Plot data
for i in range(len(x1)):
    id_map1.plot(x1[i], y1[i], 'or', markersize=10, alpha=.8)

# Save the file
plt.title(u'Mappa dei FabLab/makerspace italiani', fontsize=18, y=1.02)
plt.savefig('svg/Q004-MapOfLabsInItaly-plot01.svg')
plt.savefig('png/Q004-MapOfLabsInItaly-plot01.png')
plt.savefig('pdf/Q004-MapOfLabsInItaly-plot01.pdf')



In [ ]: