コード例 #1
0
ファイル: graphs.py プロジェクト: nantodevison/lapi
def graph_transit_filtre_multiple(df_transit_avec_filtre, date_debut, date_fin,
                                  o_d, nb_jours):
    """
    Regroupement de charts altair issues de graph_transit_filtre sur un plusieurs jours
    en entre :
        cf graph_transit_filtre
        nb_jours : integer : nb de jours à concatener
    en sortie : 
        une chart altair concatenee verticalement avec un pour chaque jour
    """
    dico_graph = {
        'graph' + str(indice): graph_transit_filtre(df_transit_avec_filtre,
                                                    str(dates[0]),
                                                    str(dates[1]), o_d)
        for indice, dates in enumerate(
            zip([
                str(x)
                for x in pd.date_range(date_debut, periods=nb_jours, freq='D')
            ], [
                str(x)
                for x in pd.date_range(date_fin, periods=nb_jours, freq='D')
            ]))
    }
    liste_graph = [dico_graph[key] for key in dico_graph.keys()]

    return alt.VConcatChart(vconcat=(liste_graph))
コード例 #2
0
def graph_trajet_multiple(dico_od, date, o_d, nb_jours):
    """
    Regroupement de charts altair issues de graph_trajet sur un plusieurs jours
    """
    dico_od_graph=dico_od.loc[(dico_od.date_cam_1.between(pd.to_datetime(date+' 00:00:00'),pd.to_datetime(date+' 23:59:59')+pd.Timedelta(str(nb_jours)+'D'))) & (
        dico_od.apply(lambda x : x['o_d']==o_d,axis=1))].copy()
    return alt.VConcatChart(vconcat=([graph_trajet(dico_od_graph,date_g.strftime('%Y-%m-%d'), o_d) 
                                      for date_g in pd.date_range(date, periods=nb_jours, freq='D')]))
コード例 #3
0
def comp_lapi_gest_multicam(df_passages_immat_ok,donnees_gest, date_d='2019-01-28', date_f='2019-02-11',
                            liste_num_cam=list(range(1,14))+[15,18,19]):  
    """
    porposer un graph unique pour toute les cmaraison gest-lapi
    en entree : la liste des cameras
    """
    return alt.VConcatChart(vconcat=[comp_lapi_gest(df_passages_immat_ok,donnees_gest, camera)
                              for camera in liste_num_cam])
コード例 #4
0
def facet_wrap(charts, charts_per_row):
    rows_of_charts = [
        charts[i:i+charts_per_row]
        for i in range(0, len(charts), charts_per_row)]
    vconcat = [make_hcc(r) for r in rows_of_charts]
    vcc = alt.VConcatChart(vconcat=vconcat)\
      .configure_axisX(grid=True)\
      .configure_axisY(grid=True)
    return vcc
コード例 #5
0
def facet_wrap(charts, charts_per_row):
    rows_of_charts = [
        charts[i:i + charts_per_row]
        for i in range(0, len(charts), charts_per_row)
    ]
    vconcat = [make_hcc(r) for r in rows_of_charts]
    vcc = alt.VConcatChart(vconcat=vconcat, padding={'left':20, 'top':5}, spacing=40)\
      .configure_axisX(grid=True)\
      .configure_axisY(grid=True)
    return vcc
コード例 #6
0
def push_report(service):
    user_email = service.users().getProfile(
        userId='me').execute()['emailAddress']
    print(user_email)
    global params
    y_bottom = np.zeros(12)
    charts = []
    df1 = pd.DataFrame()
    for company_name in params:
        company = params[company_name]
        if company_name in IGNORE_LIST or not create_dump(service, company):
            continue
        # if company_name in IGNORE_LIST:
        #     continue
        try:
            x, y = getData(company_name, company['fname'])
            x, y = coerceData(x, y)
        except Exception as e:
            print(e)
            continue
        print(company_name, y)
        y_bottom = np.add(y_bottom, y)
        source = pd.DataFrame({
            'month': x,
            'spent': y,
            'company': [company_name] * 12
        })
        chart = alt.Chart(source).mark_bar(size=15).encode(
            x=alt.X('month', title=''),
            y=alt.Y('spent',
                    title='Amount spent (₹)')).properties(title=company_name, )
        charts.append(chart)
        source.set_index('month')
        if not df1.size:
            df1 = source
        else:
            df1 = df1.append(source)
    if not df1.size:
        print('No data found for ' + user_email)
        return
    stackedchart = alt.Chart(df1).mark_bar(size=15).encode(
        alt.X('month', title=''),
        y=alt.Y('sum(spent)', title='Amount spent (₹)'),
        color='company').properties(title='Aggregate Monthly Spending')
    charts.insert(0, stackedchart)
    repchart = alt.VConcatChart(vconcat=charts)
    save(repchart,
         os.path.dirname(os.path.abspath(__file__)) + '/data/report.png',
         scale_factor=1.5)
    with app.app_context():
        context = {'amount': np.sum(y_bottom)}
        email_content = render_template('report.html', **context)
    push_email(email_content, user_email)
コード例 #7
0
def graph_transit_vl_pl_camera_multi_j(synt_nb_veh_cam, date,cam,nb_jour): 
    """
    Regroupement de charts altair issues de graph_VL_PL_transit_j_cam sur plusieurs jours
    en entre :
        cf graph_VL_PL_transit_j_cam
        nb_jours : integer : nb de jours à concatener
    en sortie : 
        une chart altair concatenee verticalement avec un pour chaque jour
    """
    dico_graph={'graph'+str(indice):graph_VL_PL_transit_j_cam(synt_nb_veh_cam, date, cam) 
               for indice,date in enumerate(zip([str(x) for x in pd.date_range(date, periods=nb_jour, freq='D')]))}
    liste_graph=[dico_graph[key] for key in dico_graph.keys()]
    return alt.VConcatChart(vconcat=(liste_graph))  
コード例 #8
0
def graph_nb_veh_ttjours_ttcam(df) : 
    """
    Fonction de graph du nb ceh par jour et par pour l'ensembles des cameras
    en entree : 
       df : la df des passages isssue de la bdd
    en sortie : 
        graph_filtre_tps : une chart altair concatenee vertical. en x les jours, en y le nb de veh 
    """
    nb_passage_j_cam=df.reset_index().set_index('created').groupby('camera_id').resample('D').count().drop('camera_id',axis=1).reset_index()
    return alt.VConcatChart(vconcat=([alt.Chart(nb_passage_j_cam.loc[nb_passage_j_cam['camera_id']==camera], title=f'camera {camera}').mark_bar(size=20).encode(
                                    x=alt.X('created',axis=alt.Axis(title='Jour', format='%A %d-%m-%y',labelAngle=45)),
                                    y=alt.Y('immat',axis=alt.Axis(title='Nombre de véhicules'))).properties(width=1000)  for camera in 
        [1,2,3,4,5,6,7,8,9,10,11,12,13,15,18,19]]))
コード例 #9
0
def graph_nb_veh_jour_camera_multi_j(df,date_debut,date_fin,cam,nb_jour, type_v='TV'): 
    """
    Regroupement de charts altair issues de graph_nb_veh_jour_camera sur plusieurs jours
    en entre :
        cf graph_nb_veh_jour_camera
        nb_jours : integer : nb de jours à concatener
    en sortie : 
        une chart altair concatenee verticalement avec un pour chaque jour
    """
    df_index_ok=df.reset_index()
    dico_graph={indice:graph_nb_veh_jour_camera(df_index_ok, dates[0], dates[1], cam, type_v) 
               for indice,dates in enumerate(zip([str(x) for x in pd.date_range(date_debut, periods=nb_jour, freq='D')],
                                [str(x) for x in pd.date_range(date_fin, periods=nb_jour, freq='D')]))}
    liste_graph=[graph for graph in {'liste_graph'+str(i):alt.HConcatChart(hconcat=([dico_graph[key] for key in dico_graph.keys() if key in range(i-7,i)])) for i in [8,15,22]}.values()]
    return alt.VConcatChart(vconcat=(liste_graph))
コード例 #10
0
def plot(df, main, new):

    print('Combining into thumbnail...')
    today = pd.to_datetime(df.iloc[-1].date).strftime('%b %d')
    nv = int(df.iloc[-1].new_vaccinated)
    v = int(df.iloc[-1].vaccinated)
    nd = int(df.iloc[-1].new)
    d = int(df.iloc[-1].total)

    thumb = alt.VConcatChart(vconcat=[main, new]).configure_view(
        strokeWidth=0).properties(
            title={
                'text': [
                    'Ontario Doses and Vaccinations',
                    f'{today}: {v:,d} people vaccinated so far'
                ],
                'subtitle': [
                    f'Total doses: {d:,}; total vaccinations: {v:,},',
                    f'New doses: {nd:,}; new vaccinations: {nv:,},',
                    '@OntVaccine by @__martinallen__'
                ]
            }).configure_title(fontSize=30, color='#66334B')

    return thumb
コード例 #11
0
"""
Interval Selection Example
==========================

This is an example of creating a stacked chart for which the domain of the
top chart can be selected by interacting with the bottom chart.
"""
# category: interactive

import altair as alt
from vega_datasets import data
sp500 = data.sp500.url

brush = alt.selection(type='interval', encodings=['x'])

upper = alt.Chart().mark_area().encode(
    x=alt.X('date:T', scale={'domain': brush.ref()}),
    y='price:Q'
).properties(
    width=600,
    height=200
)

lower = upper.properties(
    selection=brush,
    height=60
)

chart = alt.VConcatChart([upper, lower], data=sp500)
コード例 #12
0
    def get_interactive_detail_multi_line_chart(
        column_dfs: List[Tuple[str, pd.DataFrame]],
        metric_name: str,
        metric_type: alt.StandardType,
        domain_name: str,
        domain_type: alt.StandardType,
    ) -> alt.VConcatChart:
        """
        Args:
            column_dfs: A list of tuples pairing pandas dataframes with the columns they correspond to
            metric_name: The name of the metric as it exists in the pandas dataframe
            metric_type: The altair data type for the metric being plotted
            domain_name: The name of the domain as it exists in the pandas dataframe
            domain_type: The altair data type for the domain being plotted

        Returns:
            A interactive detail altair multi-line chart
        """
        metric_title: str = metric_name.replace("_", " ").title()
        domain_title: str = domain_name.title()
        title: alt.TitleParams = alt.TitleParams(
            f"{metric_title} per {domain_title}",
            dy=-30,
        )

        batch_id: str = "batch_id"
        batch_id_title: str = batch_id.replace("_", " ").title().replace("Id", "ID")
        batch_id_type: alt.StandardType = AltairDataTypes.NOMINAL.value

        column_name: str = "column_name"
        column_name_title: str = "Column Name"
        column_name_type: alt.StandardType = AltairDataTypes.NOMINAL.value

        detail_title_font_size: int = 14
        detail_title_font_weight: str = "bold"

        line_chart_height: int = 150
        detail_line_chart_height: int = 75

        point_size: int = 50

        unselected_color: alt.value = alt.value("lightgray")

        selected_opacity: float = 1.0
        unselected_opacity: float = 0.4

        tooltip: List[alt.Tooltip] = [
            alt.Tooltip(
                field=column_name, type=column_name_type, title=column_name_title
            ),
            alt.Tooltip(field=batch_id, type=batch_id_type, title=batch_id_title),
            alt.Tooltip(
                field=metric_name, type=metric_type, title=metric_title, format=","
            ),
        ]

        df: pd.DataFrame = pd.DataFrame(
            columns=[column_name, domain_name, batch_id, metric_name]
        )
        for column, column_df in column_dfs:
            column_df[column_name] = column
            df = pd.concat([df, column_df], axis=0)

        columns: List[str] = [" "] + pd.unique(df[column_name]).tolist()
        input_dropdown: alt.binding_select = alt.binding_select(
            options=columns, name="Select Column: "
        )
        selection: alt.selection_single = alt.selection_single(
            empty="none",
            bind=input_dropdown,
            fields=[column_name],
        )

        line: alt.Chart = (
            alt.Chart(df)
            .mark_line()
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    axis=alt.Axis(ticks=False, title=None, labels=False),
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                color=alt.condition(
                    selection,
                    alt.Color(
                        column_name,
                        type=AltairDataTypes.NOMINAL.value,
                        scale=alt.Scale(range=ColorPalettes.ORDINAL_7.value),
                        legend=None,
                    ),
                    unselected_color,
                ),
                opacity=alt.condition(
                    selection,
                    alt.value(selected_opacity),
                    alt.value(unselected_opacity),
                ),
                tooltip=tooltip,
            )
            .properties(height=line_chart_height, title=title)
        )

        points: alt.Chart = (
            alt.Chart(df)
            .mark_point(size=point_size)
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    axis=alt.Axis(ticks=False, title=None, labels=False),
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                color=alt.condition(
                    selection,
                    alt.value(Colors.GREEN.value),
                    unselected_color,
                ),
                opacity=alt.condition(
                    selection,
                    alt.value(selected_opacity),
                    alt.value(unselected_opacity),
                ),
                tooltip=tooltip,
            )
            .properties(height=line_chart_height, title=title)
        )

        highlight_line: alt.Chart = (
            alt.Chart(df)
            .mark_line(strokeWidth=2.5)
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    axis=alt.Axis(ticks=False, title=None, labels=False),
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                color=alt.condition(
                    selection,
                    alt.Color(
                        column_name,
                        type=AltairDataTypes.NOMINAL.value,
                        scale=alt.Scale(range=ColorPalettes.ORDINAL_7.value),
                        legend=None,
                    ),
                    unselected_color,
                ),
                opacity=alt.condition(
                    selection,
                    alt.value(selected_opacity),
                    alt.value(unselected_opacity),
                ),
                tooltip=tooltip,
            )
            .properties(height=line_chart_height, title=title)
            .transform_filter(selection)
        )

        highlight_points: alt.Chart = (
            alt.Chart(df)
            .mark_point(size=40)
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    axis=alt.Axis(ticks=False, title=None, labels=False),
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                color=alt.condition(
                    selection,
                    alt.value(Colors.GREEN.value),
                    unselected_color,
                ),
                opacity=alt.condition(
                    selection,
                    alt.value(selected_opacity),
                    alt.value(unselected_opacity),
                ),
                tooltip=tooltip,
            )
            .properties(height=line_chart_height, title=title)
            .transform_filter(selection)
        )

        detail_line: alt.Chart = (
            alt.Chart(
                df,
            )
            .mark_line(opacity=selected_opacity)
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    title=domain_title,
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                color=alt.Color(
                    column_name,
                    type=AltairDataTypes.NOMINAL.value,
                    scale=alt.Scale(range=ColorPalettes.ORDINAL_7.value),
                ),
                tooltip=tooltip,
            )
            .properties(height=detail_line_chart_height)
            .transform_filter(selection)
        )

        detail_points: alt.Chart = (
            alt.Chart(
                df,
            )
            .mark_point(
                size=point_size, color=Colors.GREEN.value, opacity=selected_opacity
            )
            .encode(
                x=alt.X(
                    domain_name,
                    type=domain_type,
                    title=domain_title,
                ),
                y=alt.Y(metric_name, type=metric_type, title=None),
                tooltip=tooltip,
            )
            .properties(height=detail_line_chart_height)
            .transform_filter(selection)
        )

        detail_title_column_names: pd.DataFrame = pd.DataFrame(
            {column_name: pd.unique(df[column_name])}
        )
        detail_title_column_titles: str = "column_title"
        detail_title_column_names[
            detail_title_column_titles
        ] = detail_title_column_names[column_name].apply(
            lambda x: f"Column ({x}) Selection Detail"
        )
        detail_title_text: alt.condition = alt.condition(
            selection, detail_title_column_titles, alt.value("")
        )

        detail_title = (
            alt.Chart(detail_title_column_names)
            .mark_text(
                color=Colors.PURPLE.value,
                fontSize=detail_title_font_size,
                fontWeight=detail_title_font_weight,
            )
            .encode(text=detail_title_text)
            .transform_filter(selection)
            .properties(height=10)
        )

        # special title for combined y-axis across two charts
        y_axis_title = alt.TitleParams(
            metric_title,
            color=Colors.PURPLE.value,
            orient="left",
            angle=270,
            fontSize=14,
            dx=70,
            dy=-5,
        )

        return (
            alt.VConcatChart(
                vconcat=[
                    line + points + highlight_line + highlight_points,
                    detail_title,
                    detail_line + detail_points,
                ],
            )
            .properties(title=y_axis_title)
            .add_selection(selection)
        )
コード例 #13
0
def draw_resid_dashboard(resids_df, target_units, cat_col, tooltip_features):

    brush = alt.selection(type='interval', resolve='global')

    max_act = resids_df["actual"].max() * 1.1
    max_pred = resids_df["pred"].max() * 1.1
    max_pred_act = max(max_act, max_pred)
    max_abs_resid = resids_df["abs_resid"].max() * 1.1

    ## Scatterplots

    scatter_base = \
    alt.Chart().mark_circle(size=70, clip=True).encode(
        x=alt.X("actual:Q", title="Actual Value", scale=alt.Scale(domain=(0, max_pred_act))),
        color=alt.condition(brush, cat_col, alt.ColorValue('gray'), legend=None),
        tooltip=tooltip_features
    ).add_selection(brush
    ).properties(
        width=610,
        height=610
    )

    # Actual vs Predicted Scatterplot
    pred_scatter = \
    scatter_base.encode(y=alt.Y("pred:Q", title="Predicted Value", scale=alt.Scale(domain=(0, max_pred_act)))
                       ).properties(title=f"Actuals vs. Predictions, colored by {cat_col}")

    identity_rule_df = pd.DataFrame([{
        "x": 0,
        "y": 0
    }, {
        "x": max_pred_act,
        "y": max_pred_act
    }])
    identity_rule = alt.Chart(identity_rule_df).mark_line(
        color="#000000", clip=True).encode(
            x=alt.X("x:Q", scale=alt.Scale(domain=(0, max_pred_act))),
            y='y:Q',
        )

    pred_scatter += identity_rule  # Draw the line on top

    # Actual vs Residual
    resid_scatter = \
    scatter_base.encode(y=alt.Y("resid:Q", title="Residual (Predicted minus Actual)", scale=alt.Scale(domain=(-max_abs_resid, max_abs_resid)))
        ).properties(title=f"Actuals vs. Residuals, colored by {cat_col}")#.interactive()

    zero_rule_df = pd.DataFrame([{
        "x": 0,
        "y": 0
    }, {
        "x": max_pred_act,
        "y": 0
    }])
    zero_rule = alt.Chart(zero_rule_df).mark_line(color="#000000").encode(
        x=alt.X("x:Q", scale=alt.Scale(domain=(0, max_pred_act))),
        y='y:Q',
    )

    resid_scatter += zero_rule  # Draw the line on top

    scatterplots = pred_scatter | resid_scatter

    ## Bar Charts

    bars_base = \
    alt.Chart().mark_bar().encode(
        y=alt.Y(f'{cat_col}:N', title=None),
        color=alt.Color(f'{cat_col}:N', legend=None)
    ).properties(
        width=350,
        height=150
    ).transform_filter(brush)

    vc_bars = bars_base.encode(
        x='count({cat_col}):Q',
        y=alt.Y(f'{cat_col}:N')).properties(title="Value Counts")
    mape_bars = bars_base.encode(
        x=alt.X('mean(abs_perc_resid):Q', title="Percent")).properties(
            title="Mean Absolute Percent Error (MAPE)")

    #Stacked bars
    avg_act_bars = bars_base.encode(alt.X('mean(actual):Q', stack=None))
    mae_bars = bars_base.encode(
        alt.X('mean(abs_resid):Q', title=target_units, stack=None),
        color=alt.value("black")).properties(
            title="Mean Absolute Error (black) vs. Mean of Target")
    avg_act_vs_mae = avg_act_bars + mae_bars

    bar_charts = alt.HConcatChart(hconcat=(vc_bars, avg_act_vs_mae,
                                           mape_bars), )

    dash = alt.VConcatChart(data=resids_df, vconcat=(scatterplots, bar_charts))

    return dash.configure_axis(labelFontSize=13,
                               titleFontSize=15,
                               labelFlush=True,
                               labelLimit=100).configure_title(fontSize=20)
コード例 #14
0
def seasonEvo1415():
    premier1415 = pd.read_csv('App/Data/premier1415.csv')
    premier1415mod = premier1415.copy()
    premier1415mod[
        'cumpoints'] = premier1415mod['cumpoints'] - premier1415mod['points']
    topteams1415 = [
        'Leicester City', 'Chelsea', 'Manchester City', 'Arsenal', 'Hull City',
        'Burnley', 'Queens Park Rangers'
    ]
    noLC = [
        'Chelsea', 'Manchester City', 'Arsenal', 'Hull City', 'Burnley',
        'Queens Park Rangers'
    ]
    LC = ['Leicester City']
    premier1415noLC = premier1415[premier1415['team_long_name'].isin(noLC)]
    premier1415LC = premier1415[premier1415['team_long_name'].isin(LC)]

    noLClast1415 = premier1415noLC[premier1415noLC['stage'] == 38]
    LClast1415 = premier1415LC[premier1415LC['stage'] == 38]
    LClast1415['position'] = '14th'
    noLClast1415['position'] = ['19th', '1st', '2nd', '18th', '3rd', '20th']

    a = {'x': [30], 'y': [19], 'textof': ['➟']}
    arrow = pd.DataFrame(a)

    palette = alt.Scale(domain=topteams1415,
                        range=[
                            '#0062cc', 'green', '#6CABDD', '#EF0107',
                            '#663f3f', '#e1d89f', '#d89216'
                        ])

    pointarrow = alt.Chart(arrow).mark_circle(size=100,
                                              color='black').encode(x='x',
                                                                    y='y')

    textarrow = alt.Chart(arrow).mark_text(dx=-20,
                                           dy=0,
                                           angle=240,
                                           fontSize=30).encode(x='x',
                                                               y='y',
                                                               text='textof')
    noLC = [
        'Chelsea', 'Manchester City', 'Arsenal', 'Queens Park Rangers',
        'Burnley', 'Hull City'
    ]
    LC = ['Leicester City']

    nearest = alt.selection(type='single',
                            nearest=True,
                            on='mouseover',
                            fields=['stage'],
                            init={'stage': 20},
                            empty='none')

    lineLC = alt.Chart(premier1415LC).mark_line(size=5).encode(
        x=alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        y=alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
        color=alt.Color('team_long_name:N', title='Team'),
        tooltip='team_long_name:N')
    line = alt.Chart(premier1415noLC).mark_line(size=2).encode(
        x=alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        y=alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
        color=alt.Color('team_long_name:N', title='Team'),
        tooltip='team_long_name:N')

    selectors = alt.Chart(premier1415).mark_point().encode(
        x='stage',
        opacity=alt.value(0),
    ).add_selection(nearest)

    labelsLC = alt.Chart(LClast1415).mark_text(
        align='left', dx=3, size=14).encode(
            alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
            alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
            alt.Text('position'),
            alt.Color('team_long_name:N', title='Team', scale=palette),
        )
    labels = alt.Chart(noLClast1415).mark_text(
        align='left', dx=3, size=12).encode(
            alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
            alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
            alt.Text('position'),
            alt.Color('team_long_name:N', title='Team', scale=palette),
        )

    points = line.mark_circle(size=80).encode(
        opacity=alt.condition(nearest, alt.value(1), alt.value(0)))
    pointsLC = lineLC.mark_circle(size=100).encode(opacity=alt.condition(
        nearest, alt.value(1), alt.value(0)), )
    rules = alt.Chart(premier1415).mark_rule(color='gray').encode(
        x='stage', ).transform_filter(nearest)

    tick = alt.Chart(premier1415mod).mark_tick(
        color='black',
        thickness=2,
        strokeDash=[1, 1],
        size=40 * 0.9,  # controls width of tick.
    ).encode(
        x=alt.X('cumpoints:Q', scale=alt.Scale(domain=[0, 81]),
                title='Points'),
        y=alt.Y('team_long_name:N',
                sort=alt.EncodingSortField("cumpoints",
                                           op="max",
                                           order='descending'),
                title='Team'),
    ).transform_filter(nearest)

    hist = alt.Chart(premier1415).mark_bar().encode(
        x=alt.X('cumpoints:Q', scale=alt.Scale(domain=[0, 81]),
                title='Points'),
        y=alt.Y('team_long_name:N',
                sort=alt.EncodingSortField("cumpoints",
                                           op="max",
                                           order='descending'),
                title='Team'),
        color=alt.Color(
            'team_long_name:N',
            scale=alt.Scale(domain=topteams1415))).transform_filter(nearest)
    text = hist.mark_text(
        align='left',
        baseline='middle',
        dx=3,  # Nudges text to right so it doesn't appear on top of the bar
        fontSize=14).encode(text='cumpoints:Q')
    text1415 = alt.Chart({
        'values': [{
            'x': 26,
            'y': 8
        }]
    }).mark_text(
        text=
        'With only 8 games left, Leicester City\n was at the bottom of the table',
        lineBreak='\n',
        align='left',
        fontSize=14
        # , angle=346
    ).encode(x='x:Q', y='y:Q')
    layer = alt.layer(lineLC, line, labels, labelsLC, selectors, points,
                      pointsLC, rules, text1415, pointarrow,
                      textarrow).properties(width=1100, height=300, title='')
    layer2 = alt.layer(hist, text, tick).properties(
        width=1120, height=300, title='Points at the selected Gameweek')
    return alt.VConcatChart(vconcat=(layer, layer2), padding={
        "left": 120
    }).configure_title(fontSize=16).configure_axis(
        labelFontSize=12,
        titleFontSize=12).configure_legend(labelFontSize=12,
                                           titleFontSize=12).to_json()
コード例 #15
0
def seasonEvolution():
    premier1516 = pd.read_csv('App/Data/premier1516.csv')
    topteams1516 = [
        'Leicester City', 'Arsenal', 'Tottenham Hotspur', 'Manchester City',
        'Chelsea'
    ]
    noLC = ['Arsenal', 'Tottenham Hotspur', 'Manchester City', 'Chelsea']
    LC = ['Leicester City']
    premier1516noLC = premier1516[premier1516['team_long_name'].isin(noLC)]
    premier1516LC = premier1516[premier1516['team_long_name'].isin(LC)]
    premier1516mod = premier1516.copy()
    premier1516mod[
        'cumpoints'] = premier1516mod['cumpoints'] - premier1516mod['points']

    noLClast = premier1516noLC[premier1516noLC['stage'] == 38]
    LClast = premier1516LC[premier1516LC['stage'] == 38]
    LClast['position'] = '1st'
    noLClast['position'] = ['10th', '4th', '3rd', '2nd']
    noLClast['labely'] = [50, 66, 70, 72]

    a = {'x': [13, 23], 'y': [28, 47], 'textof': ['➟', '➟']}
    arrow = pd.DataFrame(a)

    palette = alt.Scale(
        domain=topteams1516,
        range=['#0062cc', '#EF0107', 'yellow', '#6CABDD', "green"])

    pointarrow = alt.Chart(arrow).mark_circle(size=100,
                                              color='black').encode(x='x',
                                                                    y='y')

    textarrow = alt.Chart(arrow).mark_text(dx=-20, dy=0, angle=45,
                                           fontSize=30).encode(x='x',
                                                               y='y',
                                                               text='textof')

    nearest = alt.selection(type='single',
                            nearest=True,
                            on='mouseover',
                            fields=['stage'],
                            init={'stage': 20},
                            empty='none')

    lineLC = alt.Chart(premier1516LC).mark_line(size=5).encode(
        x=alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        y=alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
        color=alt.Color('team_long_name:N', title='Team'),
        tooltip='team_long_name:N')
    line = alt.Chart(premier1516noLC).mark_line(size=2).encode(
        x=alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        y=alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
        color=alt.Color('team_long_name:N', title='Team'),
        tooltip='team_long_name:N')

    selectors = alt.Chart(premier1516).mark_point().encode(
        x='stage', opacity=alt.value(0)).add_selection(nearest)
    points = line.mark_circle(size=80).encode(
        opacity=alt.condition(nearest, alt.value(1), alt.value(0)))

    labelsLC = alt.Chart(LClast).mark_text(align='left', dx=3, size=14).encode(
        alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        alt.Y('cumpoints:Q', title='Points', axis=alt.Axis(grid=False)),
        alt.Text('position'),
        alt.Color('team_long_name:N', title='Team', scale=palette),
    )
    labels = alt.Chart(noLClast).mark_text(align='left', dx=3, size=12).encode(
        alt.X('stage', title='Gameweek', axis=alt.Axis(grid=False)),
        alt.Y('labely:Q', title='Points', axis=alt.Axis(grid=False)),
        alt.Text('position'),
        alt.Color('team_long_name:N', title='Team', scale=palette),
    )

    pointsLC = lineLC.mark_circle(size=100).encode(opacity=alt.condition(
        nearest, alt.value(1), alt.value(0)), )
    rules = alt.Chart(premier1516).mark_rule(color='gray').encode(
        x='stage', ).transform_filter(nearest)
    hist = alt.Chart(premier1516).mark_bar().encode(
        x=alt.X('cumpoints:Q', scale=alt.Scale(domain=[0, 81]),
                title='Points'),
        y=alt.Y('team_long_name:N',
                sort=alt.EncodingSortField("cumpoints",
                                           op="max",
                                           order='descending'),
                title='Team'),
        color=alt.Color(
            'team_long_name:N',
            scale=alt.Scale(domain=topteams1516))).transform_filter(nearest)

    tick = alt.Chart(premier1516mod).mark_tick(
        color='black',
        thickness=2,
        strokeDash=[1, 1],
        size=60 * 0.9,  # controls width of tick.
    ).encode(
        x=alt.X('cumpoints:Q', scale=alt.Scale(domain=[0, 81]),
                title='Points'),
        y=alt.Y('team_long_name:N',
                sort=alt.EncodingSortField("cumpoints",
                                           op="max",
                                           order='descending'),
                title='Team'),
    ).transform_filter(nearest)

    text = hist.mark_text(
        align='left',
        baseline='middle',
        dx=3,  # Nudges text to right so it doesn't appear on top of the bar
        fontSize=14).encode(text='cumpoints:Q')
    text1516a = alt.Chart({
        'values': [{
            'x': 8.5,
            'y': 44
        }]
    }).mark_text(
        text='Leicester took the lead \n for the first time at Gameweek 13',
        lineBreak='\n',
        align='left',
        fontSize=14
        # , angle=346
    ).encode(x='x:Q', y='y:Q')
    text1516b = alt.Chart({
        'values': [{
            'x': 18,
            'y': 62
        }]
    }).mark_text(
        text=
        'At Gameweek 23 Leicester City took the lead\n once again and never looked back',
        lineBreak='\n',
        align='left',
        fontSize=14
        # , angle=346
    ).encode(x='x:Q', y='y:Q')
    layer = alt.layer(lineLC, line, labelsLC, labels, selectors, points,
                      pointsLC, rules, text1516a, text1516b, pointarrow,
                      textarrow).properties(width=1200, height=300, title='')
    layer2 = alt.layer(hist, text, tick).properties(
        width=1200, height=300, title='Points at the selected Gameweek')
    return alt.VConcatChart(vconcat=(layer, layer2), padding={
        "left": 100
    }).configure_title(fontSize=16).configure_axis(
        labelFontSize=12,
        titleFontSize=12).configure_legend(labelFontSize=12,
                                           titleFontSize=12).to_json()
コード例 #16
0
#print(enumerate(provs_json)

for index, p in enumerate(provs_json):
  name = provs[index]
  slug = ids[index]
  dates = [d['date'] for d in p]
  rate = [(d['deaths_acum']/d['cases_acum'])*100 if d['cases_acum'] != 0 else 0 for d in p]
  df = pd.DataFrame({'fecha':dates,'razon':rate})

  line = alt.Chart(df).mark_line(color='#009999').encode(x=alt.X('fecha:T', title=''), y=alt.Y('razon:Q', title='Razón de letalidad'))
  selectors = alt.Chart(df).mark_point().encode(x='fecha:T', opacity=alt.value(0)).add_selection(nearest)
  points = line.mark_point().encode(opacity=alt.condition(nearest, alt.value(1), alt.value(0)))
  text = line.mark_text(align='left', dx=5, dy=-5).encode(text=alt.condition(nearest, 'razon:Q', alt.value(' ')))
  rules = alt.Chart(df).mark_rule(color='gray').encode(x='fecha:T').transform_filter(nearest)
  graph = alt.layer(line, selectors, points, text, rules).properties(width=500, height=200, title=name)
  charts[str(slug).zfill(2)] = graph

array_charts = list(charts.values())

def make_hcc(row_of_charts):
    hconcat = [chart for chart in row_of_charts]
    hcc = alt.HConcatChart(hconcat=hconcat)
    return hcc

rows_of_charts = [array_charts[i:i+3] for i in range(0, len(array_charts), 3)]
vconcat = [make_hcc(r) for r in rows_of_charts]
compound_chart = alt.VConcatChart(vconcat=vconcat).configure_axisX(grid=True).configure_axisY(grid=True)
compound_chart.properties(title='Razon de letalidad de los casos por provincia')
compound_chart.show()
#altair_viewer.show(compound_chart)