In [37]:
import pandas as pd
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
eligible_votes = pd.read_csv("https://raw.githubusercontent.com/democratia/political_science/master/Reconstruct-Jura/Stimmberechtigte.csv", sep=";", na_values="...")
eligible_votes['Datum'], eligible_votes['Vorlage'] = eligible_votes['Datum und Vorlage'].str.split(' ', 1).str
eligible_votes['Datum'] = pd.to_datetime(eligible_votes['Datum'], infer_datetime_format=True)

classification = pd.read_csv('https://raw.githubusercontent.com/democratia/political_science/master/Daten/swissvotes-integralerdatensatz.csv', sep=";")
classification = classification.drop(classification.index[[0,624, 625, 626]]) #remove rows where we do not have results
rechtsform = classification['rechtsform'].as_matrix()
rechtsform = rechtsform[::-1]
eligible_votes['rechtsform'] = rechtsform

n_types = 5
rechtsformen = ["Alle", "Oblig. Referendum", "Fak. Referendum", "Initiative", "Gegenvorschlag"]
traces = []
buttons = []
for code, rechtsform in zip(np.arange(0, n_types), rechtsformen):
    if (code > 0):
        specific_votes = eligible_votes[eligible_votes["rechtsform"] == code]
    else:
        specific_votes = eligible_votes
    votes_per_year = specific_votes['Datum'].groupby([specific_votes.Datum.dt.year]).agg('count')

    all_years = dict(zip(votes_per_year.index, votes_per_year))
    for i in np.arange(1866, 2017, 1):
        if i not in all_years:
            all_years[i] = 0
    vis = False
    if code == 0:
        vis = True
    traces.append(go.Bar(
        x=list(all_years.keys()),
        y=list(all_years.values()),
        visible=vis,
        text="",
        name=""
    ))
    visible_list = [False]*n_types
    visible_list[code] = True    
    buttons.append(
        dict(
            args=['visible', visible_list],
            label=rechtsform,
            method='restyle'
        ))

print(len(traces))


5

In [38]:
layout = go.Layout(
        title='Entwicklung der Anzahl Abstimmungen pro Jahr',
        xaxis=dict(title='Jahr'),
        yaxis=dict(title='Anzahl Abstimmungen'),
        updatemenus=list([
            dict(
                active=0,
                x=-0.05,
                y=1,
                yanchor='top',
                buttons=buttons
            )
        ])
    )
fig = go.Figure(data=traces, layout=layout)    
py.iplot(fig, filename='anzahl-abstimmungen')


Out[38]:

In [ ]: