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]:
# Range: D16[SQ001] - D16[SQ011] - D16[other]
funding_columns = ["D16[SQ001]","D16[SQ002]","D16[SQ003]","D16[SQ004]",
"D16[SQ005]","D16[SQ006]","D16[SQ007]","D16[SQ008]",
"D16[SQ009]","D16[SQ010]","D16[SQ011]","D16[SQ012]","D16[SQ013]"]
funding_options = ['Singolo individuo privato',
'Gruppo di individui privati',
'Scuola primaria (scuola elementare)',
u'Universitá',
'Museo',
'Centro di ricerca',
"Incubatore o acceleratore d'impresa",
'Coworking',
'Impresa privata',
'Fondazione',
'Partecipazione a bando pubblico',
'Scuola secondaria di primo grado (scuola media)',
'Scuola secondaria di secondo grado (scuola superiore)']
funding = data[funding_columns]
funding.replace(u'Sì', 'Si', inplace=True) # Get rid of accented characters
funding_other = data['D16[other]'].str.lower().value_counts()
In [5]:
#funding[0:4]
In [6]:
%%capture output
# Save the output as a variable that can be saved to a file
# Gather data
funding_b = {}
for k,i in enumerate(funding_columns):
funding_b[k] = funding[i].value_counts(dropna=False)
print "Data:",funding_options[k].encode('utf-8')
print funding_b[k]
print
print "Data %:",funding_options[k].encode('utf-8')
print funding[i].value_counts(normalize=True,dropna=False)*100
print
In [7]:
# Save+show the output to a text file
%save Q016-DotazioniLab01.py str(output)
shutil.move("Q016-DotazioniLab01.py", "text/Q016-DotazioniLab01.txt")
In [8]:
yes = []
no = []
nanvalue = []
for k,i in enumerate(funding_columns):
funding_presents = funding_b[k].index.tolist()
# Convert NaN to "NaN"
for o,h in enumerate(funding_presents):
if type(h) is float:
funding_presents.pop(o)
funding_presents.append("NaN")
# Reassign new list with "NaN"
funding_b[k].index = funding_presents
# Check for empty values, and put a 0 instead
if "Si" not in funding_presents:
yes.append(0)
if "No" not in funding_presents:
no.append(0)
if "NaN" not in funding_presents:
nanvalue.append(0)
for j in funding_presents:
if j == "Si":
yes.append(funding_b[k].ix["Si"])
elif j == "No":
no.append(funding_b[k].ix["No"])
elif j == "NaN":
nanvalue.append(funding_b[k].ix["NaN"])
In [9]:
# Plot the data
plt.figure(figsize=(8,6))
plt.xlabel(u'Finanziatori', fontsize=16)
plt.ylabel(u'Lab', fontsize=16)
plt.title(u'Da dove provengono le risorse che hanno permesso la nascita del laboratorio?', fontsize=18, y=1.02)
plt.xticks(range(len(funding_options)),funding_options,rotation=90)
ind = np.arange(len(funding_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("svg/Q016-DotazioniLab01.svg")
plt.savefig("png/Q016-DotazioniLab01.png")
plt.savefig("pdf/Q016-DotazioniLab01.pdf")
In [10]:
%%capture output
# Save the output as a variable that can be saved to a file
# Get "other" data
funding_other = data["D16[other]"].str.lower().value_counts()
print "Data:"
print funding_other
print ""
print "Data %:"
print data["D16[other]"].str.lower().value_counts(normalize=True) * 100
In [11]:
# Save+show the output to a text file
%save Q016-DotazioniLab02.py str(output)
shutil.move("Q016-DotazioniLab02.py", "text/Q016-DotazioniLab02.txt")
In [12]:
# Plot bar
plt.figure(figsize=(8,6))
plt.title(u'Da dove provengono le risorse che hanno permesso la nascita del laboratorio? Altro', fontsize=18, y=1.02)
plt.xticks(range(len(funding_other.index)),funding_other.index,rotation=90)
plt.xlabel('Finanziatori', fontsize=16)
plt.ylabel('Lab', fontsize=16)
ind = np.arange(len(funding_other)) # the x locations for the groups
width = 0.35 # the width of the bars
my_colors = seaborn.color_palette("husl", len(funding_other)) # Set color palette
rect1 = plt.bar(ind,funding_other,width,color=my_colors,align='center')
plt.savefig("svg/Q016-DotazioniLab02.svg")
plt.savefig("png/Q016-DotazioniLab02.png")
plt.savefig("pdf/Q016-DotazioniLab02.pdf")
In [12]: