Q011 - Quali altre attività condividono la sede del laboratorio?


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

# Render our plots inline
%matplotlib inline 

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn
import shutil

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'})

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

In [3]:
# Check data
#data[0:4] # Equals to data.head()

In [4]:
1# Range: D11[SQ001] - D10[SQ005] - D11[other]

activity_columns = ["D11[SQ001]","D11[SQ002]","D11[SQ003]","D11[SQ004]","D11[SQ005]"]
activity_options = ['Coworking',
               'Botteghe artigiane',
               'Studi di progettazione',
               'Studi di prototipazione',
               'Servizi di produzione']
activity = data[activity_columns]
activity.replace(u'Sì', 'Si', inplace=True) # Get rid of accented characters 
activity_other = data['D11[other]'].str.lower().value_counts()


-c:10: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [5]:
#lab[0:4]

In [6]:
%%capture output

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

for k,i in enumerate(activity_columns):
    activity_b[k] = activity[i].value_counts(dropna=False)
    print "Data:",activity_options[k]
    print activity_b[k]
    print
    print "Data %:",activity_options[k]
    print activity[i].value_counts(normalize=True,dropna=False)*100
    print

In [7]:
# Save+show the output to a text file
%save Q011-AttivitáLab01.py str(output)
shutil.move("Q011-AttivitáLab01.py", "text/Q011-AttivitáLab01.txt")


The following commands were written to file `Q011-AttivitáLab01.py`:
Data: Coworking
No     44
Si     26
NaN     0
dtype: int64

Data %: Coworking
No     62.857143
Si     37.142857
NaN     0.000000
dtype: float64

Data: Botteghe artigiane
No     56
Si     14
NaN     0
dtype: int64

Data %: Botteghe artigiane
No     80
Si     20
NaN     0
dtype: float64

Data: Studi di progettazione
No     47
Si     23
NaN     0
dtype: int64

Data %: Studi di progettazione
No     67.142857
Si     32.857143
NaN     0.000000
dtype: float64

Data: Studi di prototipazione
No     42
Si     28
NaN     0
dtype: int64

Data %: Studi di prototipazione
No     60
Si     40
NaN     0
dtype: float64

Data: Servizi di produzione
No     57
Si     13
NaN     0
dtype: int64

Data %: Servizi di produzione
No     81.428571
Si     18.571429
NaN     0.000000
dtype: float64



In [8]:
yes = []
no = []
nanvalue = []

for k,i in enumerate(activity_columns):
    activity_presents = activity_b[k].index.tolist()
    
    # Convert NaN to "NaN"
    for o,h in enumerate(activity_presents):
        if type(h) is float:
            activity_presents.pop(o)
            activity_presents.append("NaN")
    
    # Reassign new list with "NaN"
    activity_b[k].index = activity_presents
    
    # Check for empty values, and put a 0 instead
    if "Si" not in activity_presents:
        yes.append(0)
    if "No" not in activity_presents:
        no.append(0)
    if "NaN" not in activity_presents:
        nanvalue.append(0)
    
    for j in activity_presents:
        if j == "Si":
            yes.append(activity_b[k].ix["Si"])
        elif j == "No":
            no.append(activity_b[k].ix["No"])
        elif j == "NaN":
            nanvalue.append(activity_b[k].ix["NaN"])

In [9]:
# Plot the data
plt.figure(figsize=(8,6))
plt.xlabel(u'Attivitá', fontsize=16)
plt.ylabel(u'Lab', fontsize=16)
plt.title(u'Quali altre attività condividono la sede del laboratorio?', fontsize=18, y=1.02)
plt.xticks(range(len(activity_options)),activity_options,rotation=90)
ind = np.arange(len(activity_columns))   # the x locations for the groups
width = 0.25                              # the width of the bars

my_colors = seaborn.color_palette("Set1", 3) # Set color palette
rect1 = plt.bar(ind,yes,width,color=my_colors[1],align='center') # Plot Yes
rect2 = plt.bar(ind+width,no,width,color=my_colors[0],align='center') # Plot No 
rect3 = plt.bar(ind+width*2,nanvalue,width,color=my_colors[2],align='center') # Plot NaN 
plt.legend( (rect1, rect2, rect3), ('Si', 'No', 'Nessuna risposta') )
plt.savefig(u"svg/Q011-AttivitáLab01.svg")
plt.savefig(u"png/Q011-AttivitáLab01.png")
plt.savefig(u"pdf/Q011-AttivitáLab01.pdf")



In [10]:
%%capture output

# Save the output as a variable that can be saved to a file
# Get "other" data
activity_other = data["D11[other]"].str.lower().value_counts()
print "Data:"
print activity_other
print ""
print "Data %:"
print data["D11[other]"].str.lower().value_counts(normalize=True) * 100

In [11]:
# Save+show the output to a text file
%save Q011-AttivitáLab02.py str(output)
shutil.move("Q011-AttivitáLab02.py", "text/Q011-AttivitáLab02.txt")


The following commands were written to file `Q011-AttivitáLab02.py`:
Data:
accademia della scala, scuola di moda, centro di formazione     1
nessuna                                                         1
nessuna convivenza con altre attività strutturate               1
fondazione                                                      1
laboratori scuole                                               1
atelier                                                         1
caffè letterario, falegnameria, sala d'arte, laboratorio sartoria digitale    1
aula studio, corsi                                              1
laboratori teatrali, laboratori didattici                       1
laboratori creativi e didattici                                 1
ricerca scientifica, amministrazione                            1
fablab                                                          1
dtype: int64

Data %:
accademia della scala, scuola di moda, centro di formazione     1.428571
nessuna                                                         1.428571
nessuna convivenza con altre attività strutturate               1.428571
fondazione                                                      1.428571
laboratori scuole                                               1.428571
atelier                                                         1.428571
caffè letterario, falegnameria, sala d'arte, laboratorio sartoria digitale    1.428571
aula studio, corsi                                              1.428571
laboratori teatrali, laboratori didattici                       1.428571
laboratori creativi e didattici                                 1.428571
ricerca scientifica, amministrazione                            1.428571
fablab                                                          1.428571
dtype: float64


In [12]:
# Plot bar
plt.figure(figsize=(8,6))
plt.title(u'Quali altre attività condividono la sede del laboratorio? Altro', fontsize=18, y=1.02)
plt.xticks(range(len(activity_other.index)),activity_other.index,rotation=90)
plt.xlabel(u'Attivitá', fontsize=16)
plt.ylabel('Lab', fontsize=16)
ind = np.arange(len(activity_other))   # the x locations for the groups
width = 0.35                       # the width of the bars

my_colors = seaborn.color_palette("husl", len(activity_other)) # Set color palette
rect1 = plt.bar(ind,activity_other,width,color=my_colors,align='center')
plt.savefig(u"svg/Q011-AttivitáLab02.svg")
plt.savefig(u"png/Q011-AttivitáLab02.png")
plt.savefig(u"pdf/Q011-AttivitáLab02.pdf")