def world_map_for_factors(highlight, dataset, select_year):

    cols = alt.hconcat()
    for val in dataset:
        map = alt.Chart(df).mark_geoshape(
            stroke='#aaa', strokeWidth=0.25
        ).encode(
            x = alt.X("Country Name"),
            color=alt.condition(highlight, val, alt.value('lightgrey'), scale=alt.Scale(scheme='yelloworangered'), title=""),
            tooltip=["Country Name"] + dataset
        ).transform_lookup(
            lookup='Country Name',
            from_=alt.LookupData(
                "https://raw.githubusercontent.com/KoGor/Map-Icons-Generator/master/data/world-110m-country-names.tsv",
                'name', ['id', "name"])
        ).transform_lookup(
            lookup='id',
            from_=alt.LookupData(countries, 'id', fields=["id", "type", "properties", "geometry"])
        ).project(
            type="equirectangular"
        ).properties(
            width=500,
            height=200,
            title=val,
        ).add_selection(select_year, highlight) \
            .transform_filter(select_year)

        cols &= map
    return cols.resolve_scale(color='independent')
def world_map(highlight, highlight2):
    slider = alt.binding_range(min=1991, max=2011, step=1)
    select_year = alt.selection_single(name="Year",
                                       fields=['Year'],
                                       bind=slider,
                                       init={'Year': 2011})

    map = alt.Chart(df).mark_geoshape(stroke='#aaa', strokeWidth=0.25).encode(
        color=alt.condition(highlight2 | highlight,
                            'CO2 emissions (kt):Q',
                            alt.value('lightgrey'),
                            scale=alt.Scale(scheme='redyellowblue',
                                            reverse=True)),
        tooltip=[
            "Country Name", "CO2 emissions (kt)", "CO2 emissions per capita"
        ]
    ).transform_lookup(
        lookup='Country Name',
        from_=alt.LookupData(
            "https://raw.githubusercontent.com/KoGor/Map-Icons-Generator/master/data/world-110m-country-names.tsv",
            'name', ['id', "name"])).transform_lookup(
                lookup='id',
                from_=alt.LookupData(
                    countries,
                    'id',
                    fields=["id", "type", "properties", "geometry"])
            ).project(type="equirectangular").properties(
                width=1100,
                height=650,
                title='worldwide CO2 total emissions and emissions per capita'
            ).add_selection(highlight, highlight2)

    percapita = alt.Chart(df).mark_circle(opacity=0.4, ).encode(
        size=alt.Size('CO2 emissions per capita:Q',
                      scale=alt.Scale(range=[10, 3000])),
        color=alt.condition(highlight2 | highlight, alt.value('red'),
                            alt.value('lightgrey')),
        longitude='Longitude (average):Q',
        latitude='Latitude (average):Q',
        tooltip=[
            "Country Name", "CO2 emissions (kt)", "CO2 emissions per capita"
        ]
    ).transform_lookup(
        lookup='Country Name',
        from_=alt.LookupData(
            "https://raw.githubusercontent.com/KoGor/Map-Icons-Generator/master/data/world-110m-country-names.tsv",
            'name', ['id', "name"])).transform_lookup(
                lookup='id',
                from_=alt.LookupData(
                    countries,
                    'id',
                    fields=["id", "type", "properties", "geometry"
                            ])).project(type="equirectangular").properties(
                                width=900,
                                height=400,
                            )
    return alt.layer(map, percapita) \
        .add_selection(select_year) \
        .transform_filter(select_year)
Exemple #3
0
def cumulative_per_100k_over_time(metric, data, county_list=None):

    if metric == 'Incidence':
        st.write('## Cumulative Cases per 100K People Over Time')
        st.write('')
        st.write('')

        core_metric = 'cases'
    elif metric == 'Mortality':
        st.write('## Cumulative Deaths per 100K People Over Time')
        st.write('')
        st.write('')

        core_metric = 'deaths'

    selection = alt.selection_single(on='mouseover', empty='none')

    if county_list == None:
        chloropleth_map = alt.Chart(counties).mark_geoshape(
            stroke='grey').encode(
                color=alt.condition(selection, alt.value('black'),
                                    core_metric + '-per-100K:Q'),
                tooltip=[
                    '[properties][NAME]:N', core_metric + ':Q', 'population:Q',
                    core_metric + '-per-100K:Q'
                ]).transform_lookup(
                    lookup='[properties][NAME]',
                    from_=alt.LookupData(
                        data[data['date'] == date_value], 'county',
                        [core_metric, 'population', core_metric + '-per-100K'
                         ])).properties(width=800,
                                        height=600).add_selection(selection)

    else:
        chloropleth_map = alt.Chart(counties).mark_geoshape(
            stroke='grey').encode(
                color=alt.condition(selection, alt.value('black'),
                                    core_metric + '-per-100K:Q'),
                tooltip=[
                    '[properties][NAME]:N', core_metric + ':Q', 'population:Q',
                    core_metric + '-per-100K:Q'
                ]).transform_lookup(
                    lookup='[properties][NAME]',
                    from_=alt.LookupData(
                        data[data['date'] == date_value], 'county',
                        [core_metric, 'population', core_metric + '-per-100K'
                         ])).properties(width=800, height=600).add_selection(
                             selection).transform_filter(
                                 alt.FieldOneOfPredicate(
                                     field='[properties][NAME]',
                                     oneOf=county_list))

    render = st.altair_chart(chloropleth_map, use_container_width=False)
    return render
def draw_v1():
    # slider for selecting specific years
    cnt_df = pd.read_csv("data/loc_time_join.csv")

    sum_avg_df = pd.read_csv("data/avg_loc_time_join.csv")

    year = st.slider("Year", min_value=2013, max_value=2018, step=1)

    # A slider filter
    # year_slider = alt.binding_range(min=2013, max=2018, step=1)
    # slider_selection = alt.selection_single(bind=year_slider, fields=['Post year'])

    # get count agg by the given year range
    cnt_filter_df = cnt_df[cnt_df['Post year'] == year]

    sum_avg_filter_df = sum_avg_df[sum_avg_df['Post Year'] == year]
    #make a map
    states = alt.topo_feature(data.us_10m.url, 'states')

    count_v = alt.Chart(states).mark_geoshape(
        stroke='#aaa', strokeWidth=0.25).encode(
            color='Count:Q', tooltip=['State:N', 'Count:Q']).transform_lookup(
                lookup='id',
                from_=alt.LookupData(
                    cnt_filter_df, 'id',
                    ['Count', 'State'])).project(type='albersUsa').properties(
                        width=400, height=200)

    sum_v = alt.Chart(states).mark_geoshape(
        stroke='#aaa', strokeWidth=0.25).encode(
            color='Sum:Q', tooltip=['State:N', 'Sum:Q']).transform_lookup(
                lookup='id',
                from_=alt.LookupData(
                    sum_avg_filter_df, 'id',
                    ['Sum', 'State'])).project(type='albersUsa').properties(
                        width=400, height=200)

    avg_v = alt.Chart(states).mark_geoshape(
        stroke='#aaa', strokeWidth=0.25).encode(
            color='Average:Q',
            tooltip=['State:N', 'Average:Q']).transform_lookup(
                lookup='id',
                from_=alt.LookupData(
                    sum_avg_filter_df, 'id', ['Average', 'State'])).project(
                        type='albersUsa').properties(width=400, height=200)
    st.write(count_v)
    st.write(sum_v)
    st.write(avg_v)
    return
    def make_chart(self, df):
        variables = [
            'Casos nuevos (último boletín)',
            'Casos nuevos (últimos 7 boletines)'
        ]
        municipalities = self.geography()

        return alt.Chart(municipalities).transform_lookup(
            lookup='properties.NAME',
            from_=alt.LookupData(df, 'Municipio', variables),
            default='0'
        ).mark_geoshape().encode(
            color=alt.Color(
                alt.repeat('row'),
                type='quantitative',
                sort="descending",
                scale=alt.Scale(
                    type='symlog',
                    scheme='redgrey',
                    domainMid=0,
                    # WORKAROUND: Set the domain manually to forcibly
                    # include zero or else we run into
                    # https://github.com/vega/vega-lite/issues/6544
                    domain=alt.DomainUnionWith(unionWith=[0])),
                legend=alt.Legend(orient='left',
                                  titleLimit=400,
                                  titleOrient='left')),
            tooltip=[
                alt.Tooltip(field='properties.NAME', type='nominal'),
                alt.Tooltip(alt.repeat('row'), type='quantitative')
            ]).properties(width=575,
                          height=200).repeat(row=variables).resolve_scale(
                              color='independent').configure_view(
                                  strokeWidth=0).configure_concat(spacing=80)
Exemple #6
0
    def plot_map(area_type, width=500, height=300):
        map_json = alt.topo_feature(
            'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-50m.json',
            'countries')

        country_map = alt.Chart(
            data, title=f'# Respondents by {area_type}').transform_filter(
                col1_brush).transform_filter(col2_brush).transform_lookup(
                    lookup='CountryCode',
                    from_=alt.LookupData(map_json, 'properties.id'),
                    as_='geom',
                    default='Other').transform_aggregate(
                        counter='count()',
                        groupby=['geom', area_type]).transform_calculate(
                            geometry='datum.geom.geometry',
                            type='datum.geom.type').transform_filter(
                                alt.datum.date == 2018).mark_geoshape().encode(
                                    color='counter:Q',
                                    tooltip=[
                                        alt.Tooltip(f'{area_type}:N',
                                                    title='Area'),
                                        alt.Tooltip('counter:Q',
                                                    title='# Respondents')
                                    ]).properties(width=width, height=width)

        borders = alt.Chart(map_json).mark_geoshape(fill='#EEEEEE',
                                                    stroke='gray',
                                                    strokeWidth=1).properties(
                                                        width=width,
                                                        height=height)

        return (borders + country_map)
Exemple #7
0
def norway_plot():
    # Get covids numbers
    df = covids_numbers()

    # Gets the topojson of norway counties from random gitub
    counties = alt.topo_feature("https://raw.githubusercontent.com/deldersveld/topojson/master/countries/norway/norway-new-counties.json", "Fylker")

    # Define nearest selection (used for the highlighting)
    nearest = alt.selection(type="single", on="mouseover", fields=["properties.navn"], empty="none")

    # Plot the map
    fig = alt.Chart(counties).mark_geoshape().encode(
	# Enable hover efect
	tooltip=[
	    alt.Tooltip("properties.navn:N", title="County"),
	    alt.Tooltip("Insidens:Q", title="Cases per 100k capita"),
	],
	color=alt.Color("Insidens:Q", scale=alt.Scale(scheme="reds"), 
			legend=alt.Legend(title="Cases per 100k capita")),
	stroke=alt.condition(nearest, alt.value("gray"), alt.value(None)),
	opacity=alt.condition(nearest, alt.value(1), alt.value(0.8)),

    # Lookup number of cases from Pandas table and map to counties
    ).transform_lookup(
	lookup="properties.navn",
	from_=alt.LookupData(df, "Category", ["Insidens"])
    ).properties(
	width=500,
	height=600,
	title="Number of cases per 100k in every county",
    ).add_selection(
	nearest
    )

    return fig
Exemple #8
0
def create_plot(topo_data,
                data,
                column_name,
                data_type,
                tooltip_columns=None,
                stroke='darkgrey',
                strokeWidth=0.9,
                legend_title=None,
                scheme='reds',
                missing_color='white'):
    lookup_columns = [column_name]
    if tooltip_columns is not None:
        lookup_columns.extend(tooltip_columns)
    if legend_title is None:
        legend_title = column_name
    base = alt.Chart(topo_data) \
            .mark_geoshape() \
            .encode(
                color=alt.Color(f'{column_name}:{data_type}',
                                legend=alt.Legend(title=legend_title),
                                scale=alt.Scale(scheme=scheme)),
                tooltip=[f'{column}:N' for column in tooltip_columns],
            ).transform_lookup(
                lookup='properties.CODE_INS',
                from_=alt.LookupData(data, 'niscode', lookup_columns)
            ).properties(
                width=600,
                height=450,
            )
    return alt.Chart(topo_data).mark_geoshape(stroke=stroke, strokeWidth=strokeWidth) \
            .encode(
                color=alt.value(missing_color),
                opacity=alt.value(0.9),
            ) + base
Exemple #9
0
def plot_worldmap(year_range):
    df1 = dataset_df.copy()
    world = data.world_110m()
    world_map = alt.topo_feature(data.world_110m.url, "countries")
    chosen_ending_year = year_range[1]

    country_ids = pd.read_csv(
        "https://raw.github.ubc.ca/MDS-2020-21/DSCI_532_viz-2_students/master/data/country-ids.csv?token=AAAANV4AYXPDYXASWHWFLDLACHCJK"
    )
    df1 = pd.merge(df1, country_ids, left_on="country",
                   right_on="name").iloc[:, :-1]
    df1 = df1[df1["year"] == chosen_ending_year]

    map_click = alt.selection_multi()
    chart = (alt.Chart(world_map).mark_geoshape(xOffset=2).transform_lookup(
        lookup="id",
        from_=alt.LookupData(
            df1, "id", ["life_expectancy", "country"])).encode(
                tooltip=[
                    alt.Tooltip("country:N", title="Country"),
                    alt.Tooltip("life_expectancy:Q", title="Life Exp")
                ],
                color=alt.Color("life_expectancy:Q", legend=None),
                opacity=alt.condition(map_click, alt.value(1), alt.value(0.2)),
            ).add_selection(map_click).project("equalEarth",
                                               scale=100).properties(
                                                   width=475,
                                                   height=475,
                                               ).configure_view(strokeWidth=0))
    return chart.to_html()
def update_world_chart(year, stat_type, include_usa, gdp_pct):
    arms_df_tmp = arms_gdp if include_usa else arms_gdp.query("Country != 'USA'")
    # arms_df_tmp = pd.merge(arms_df_tmp, alt_country_ids, left_on='Country', right_on='name', how='right')
    map_stat = 'percent_GDP' if gdp_pct else 'USD_Value'
    map_legend = '% GDP' if gdp_pct else 'USD Value'
    print(year, stat_type, include_usa, gdp_pct)
    chart = alt.Chart(world_map_skl).mark_geoshape().encode(
        alt.Color(map_stat + ':Q', scale=alt.Scale(scheme='goldorange'), legend=alt.Legend(title=map_legend))
    ).transform_lookup(
        lookup='id',
        from_=alt.LookupData(arms_df_tmp.query("Year == " + str(year)).query("Direction == '%s'" % (stat_type)), 'id',
                             [map_stat])
    ).project('equirectangular').properties(
        width=720,
        height=300,
        background='white'
    ).configure_axis(
        grid=False
    )

    return html.Iframe(
        sandbox='allow-scripts',
        id='plot',
        width='900',
        height='350',
        style={'border-width': '0'},
        srcDoc=chart.to_html()
    )
Exemple #11
0
def plot_altair(selected_province, price_value, points_value):
    if selected_province == 'Select your province':
        df_filtered = df
    else:
        df_filtered = df[df['state'] == selected_province]

    state_map = alt.topo_feature(data.us_10m.url, 'states')
    df_filtered = df_filtered[(df_filtered['price'] >= min(price_value))
                              & (df_filtered['price'] <= max(price_value))]
    df_filtered = df_filtered[(df_filtered['points'] >= min(points_value))
                              & (df_filtered['points'] <= max(points_value))]
    states_grouped = df_filtered.groupby(['state', 'state_id'], as_index=False)
    wine_states = states_grouped.agg({
        'points': ['mean'],
        'price': ['mean'],
        'value': ['mean'],
        'description': ['count']
    })

    wine_states.columns = wine_states.columns.droplevel(level=1)
    wine_states = wine_states.rename(
        columns={
            "state": "State",
            "state_id": "State ID",
            "description": "Num Reviews",
            "points": 'Ave Rating',
            "price": 'Ave Price',
            "value": 'Ave Value'
        })
    map_click = alt.selection_multi(fields=['state'])
    states = alt.topo_feature(data.us_10m.url, "states")

    colormap = alt.Scale(domain=[0, 100, 1000, 2000, 4000, 8000, 16000, 32000],
                         range=[
                             '#C7DBEA', '#CCCCFF', '#B8AED2', '#3A41C61',
                             '#9980D4', '#722CB7', '#663399', '#512888'
                         ])

    foreground = alt.Chart(states).mark_geoshape().encode(
        color=alt.Color('Num Reviews:Q', scale=colormap),
        tooltip=[
            alt.Tooltip('State:O'),
            alt.Tooltip('Ave Rating:Q', format='.2f'),
            alt.Tooltip('Ave Price:Q', format='$.2f'),
            alt.Tooltip('Ave Value:Q', format='.2f'),
            alt.Tooltip('Num Reviews:Q')
        ]).mark_geoshape(stroke='black', strokeWidth=0.5).transform_lookup(
            lookup='id',
            from_=alt.LookupData(wine_states, 'State ID', [
                'State', 'State ID', 'Ave Rating', 'Ave Price', 'Ave Value',
                'Num Reviews'
            ])).project(type='albersUsa')

    background = alt.Chart(states).mark_geoshape(
        fill='gray', stroke='dimgray').project('albersUsa')
    chart = (background + foreground).configure_view(
        height=400, width=570, strokeWidth=4,
        fill=None, stroke=None).encode(opacity=alt.condition(
            map_click, alt.value(1), alt.value(0.2))).add_selection(map_click)
    return chart.to_html()
Exemple #12
0
def plot_map(country=None):
    #wine_country = pd.DataFrame()
    #if country:
    #    wine_country = wine_df[wine_df['country'] == country]
    #else:
    #   wine_country = wine_df

    wine_countryid = wine_df.merge(country_ids,
                                   left_on='country',
                                   right_on='name',
                                   how='left')
    wine_countryid = wine_countryid.value_counts(
        ['id']).reset_index(name='wine_count')

    alt.renderers.enable('default')
    world = data.world_110m()
    world_map = alt.topo_feature(data.world_110m.url, 'countries')

    chart = (alt.Chart(world_map).mark_geoshape().transform_lookup(
        lookup='id',
        from_=alt.LookupData(
            wine_countryid, 'id',
            ['wine_count'])).encode(color='wine_count:Q').project('equalEarth',
                                                                  scale=90))
    return chart.to_html()
Exemple #13
0
def update_world_chart(year, stat_type, include_usa, gdp_pct):
    map_stat = 'percent_GDP' if gdp_pct else 'USD_Value'
    map_legend = '% GDP' if gdp_pct else 'USD Value'
    arms_df_tmp = arms_gdp.copy()
    if not include_usa:
        arms_df_tmp.loc[arms_df_tmp['Country'] == 'USA', map_stat] = 0

    print(year, stat_type, include_usa, gdp_pct)
    chart = alt.Chart(world_map_skl).mark_geoshape(stroke='white').encode(
        color=alt.condition(alt.FieldEqualPredicate(field=map_stat, equal=0),
                            alt.value('lightgray'), map_stat + ':Q',
                            scale=alt.Scale(scheme='goldorange'),
                            legend=alt.Legend(title=map_legend)),
        tooltip=['Country:N', map_stat + ':Q']
    ).transform_lookup(
        lookup='id',
        from_=alt.LookupData(arms_df_tmp.query("Year == " + str(year)).query("Direction == '%s'" % (stat_type)), 'id',
                             [map_stat, 'Country'])
    ).project('equirectangular').properties(
        width=720,
        height=300,
        background='white'
    ).configure_axis(
        grid=False
    )

    return html.Iframe(
        sandbox='allow-scripts',
        id='plot',
        width='900',
        height='350',
        style={'border-width': '0'},
        srcDoc=chart.to_html()
    )
Exemple #14
0
def create_plot(topo_data,
                data,
                column_name,
                data_type,
                tooltip_columns=None,
                stroke='lightgrey',
                strokeWidth=0.5,
                legend_title=None,
                scheme='reds'):
    lookup_columns = [column_name]
    if tooltip_columns is not None:
        lookup_columns.extend(tooltip_columns)
    if legend_title is None:
        legend_title = column_name
    return alt.Chart(topo_data)\
            .mark_geoshape(stroke=stroke, strokeWidth=strokeWidth)\
            .encode(
                color=alt.Color(f'{column_name}:{data_type}',
                                legend=alt.Legend(title=legend_title),
                                scale=alt.Scale(scheme=scheme)),
                tooltip=[f'{column}:N' for column in tooltip_columns],
            ).transform_lookup(
                lookup='properties.CODE_INS',
                from_=alt.LookupData(data, 'niscode', lookup_columns)
            )
Exemple #15
0
def plot_worldmap(year_range):
    df1 = dataset_df.copy()
    world = data.world_110m()
    world_map = alt.topo_feature(data.world_110m.url, "countries")
    chosen_ending_year = year_range[1]

    country_ids = pd.read_csv(
        "data/processed/country-ids.csv"
    )
    df1 = pd.merge(df1, country_ids, left_on="country", right_on="name").iloc[:, :-1]
    df1 = df1[df1["year"] == chosen_ending_year]

    map_click = alt.selection_multi()
    chart = (
        alt.Chart(world_map)
        .mark_geoshape(xOffset=2)
        .transform_lookup(
            lookup="id", from_=alt.LookupData(df1, "id", ["life_expectancy", "country"])
        )
        .encode(
            tooltip=["country:N", "life_expectancy:Q"],
            color=alt.Color("life_expectancy:Q", title = "Life Expectancy"),
            opacity=alt.condition(map_click, alt.value(1), alt.value(0.2)),
        )
        .add_selection(map_click)
        .project("equalEarth", scale=140)
        .properties(width = 625, height = 445,)
        .configure_view(strokeWidth=0)
    )
    return chart.to_html()
Exemple #16
0
def create_map_series(df):
    # Note that a LayeredChart cannot contain faceted charts as its elements.
    # Therefore, we cannot use a basemap in this configuration, since it would produce an invalid specification.
    # More info: https://github.com/altair-viz/altair/issues/785

    df2 = df.groupby('context').mean()
    df2['context'] = df2.index
    print(df2)

    grid = alt.topo_feature(
        'https://raw.githubusercontent.com/anitagraser/sandbox/master/grid40.topojson',
        'grid40')
    variable_list = [
        'distance_error', 'along_track_error', 'cross_track_error'
    ]
    map_chart = alt.Chart(grid, title=SHIPTYPE).mark_geoshape(
        stroke='white', strokeWidth=2).encode(
            alt.Color(
                alt.repeat('column'),
                type='quantitative',
                scale=alt.Scale(domain=(0, 2000)))).transform_lookup(
                    lookup='properties.id',
                    from_=alt.LookupData(
                        df2, 'context',
                        variable_list)).project(type='mercator').properties(
                            width=300, height=200).repeat(
                                column=variable_list).resolve_scale(
                                    color='shared')

    with open(INPUT.replace('.csv', '_{}_map_series.vega'.format(SHIPTYPE)),
              'w') as map_output:
        map_output.write(map_chart.to_json(indent=2))
def get_map(variable):
    return alt.Chart(states).mark_geoshape().encode(
        alt.Color(variable, type='quantitative')).transform_lookup(
            lookup='id',
            from_=alt.LookupData(source, 'id', [variable])).properties(
                width=500,
                height=300).project(type='albersUsa').repeat(row=[variable])
def plot_norway():
    """ Makes a interactive geomap of norway with number of cases per 100k in every county.

    :return: the html file showing interactive geomap.
    """

    data = pd.read_csv("resources/covid_rate_per_100000.csv",
                       sep=';',
                       index_col=False)
    county_list = data["Category"].to_list()
    insidens_list = [
        float(i.replace(',', '.')) for i in data["Insidens"].to_list()
    ]

    data_as_dict = {"Category": county_list, "Insidens": insidens_list}
    df = pd.DataFrame.from_dict(data_as_dict)

    counties = alt.topo_feature(
        "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/norway/norway-new-counties.json",
        "Fylker")

    nearest = alt.selection(type="single",
                            on="mouseover",
                            fields=["properties.navn"],
                            empty="none")

    fig = alt.Chart(counties).mark_geoshape().encode(
        tooltip=[
            alt.Tooltip("properties.navn:N", title="County"),
            alt.Tooltip("Insidens:Q", title="Cases per 100k capita"),
        ],
        color=alt.Color("Insidens:Q",
                        scale=alt.Scale(scheme="reds"),
                        legend=alt.Legend(title="Cases per 100k capita")),
        stroke=alt.condition(nearest, alt.value("gray"), alt.value(None)),
        opacity=alt.condition(nearest, alt.value(1), alt.value(0.8)),
    ).transform_lookup(
        lookup="properties.navn",
        from_=alt.LookupData(df, "Category", ["Insidens"])).properties(
            width=700,
            height=800,
            title="Number of cases per 100k in every county",
        ).add_selection(nearest)

    fig.save("templates/interactive_map.html")

    soup = BeautifulSoup(open("templates/interactive_map.html"), 'html.parser')

    head = soup.find('head')
    body = soup.find('body')
    script = soup.find('body').find('script')

    return render_template(
        "map.html",
        head=head,
        body=body,
        script=script,
        from_date=from_date,
        to_date=to_date,
    )
def global_covid_map(cc_m):
    world_source = cc_m

    source = alt.topo_feature(data.world_110m.url, "countries")
    background = alt.Chart(source).mark_geoshape(fill="white")

    foreground = (alt.Chart(source).mark_geoshape(
        stroke="black", strokeWidth=0.15).encode(
            color=alt.Color(
                "TotalConfirmed:N",
                scale=alt.Scale(scheme="redpurple"),
                legend=None,
            ),
            tooltip=[
                alt.Tooltip("Country:N", title="Country"),
                alt.Tooltip("TotalConfirmed:Q", title="confirmed cases"),
            ],
        ).transform_lookup(
            lookup="id",
            from_=alt.LookupData(world_source, "id",
                                 ["TotalConfirmed", "Country"]),
        ))

    final_map = ((background + foreground).configure_view(
        strokeWidth=0).properties(width=700,
                                  height=400).project("naturalEarth1"))
    final_map_json = final_map.to_json()
    return final_map_json
def _rankingmap_altair(countries,
                       ranking,
                       x,
                       scenario=None,
                       method='number',
                       title='',
                       label=''):
    # Adapted from https://altair-viz.github.io/gallery/index.html

    import pandas as pd
    import altair as alt

    if method not in ['number', 'value']:
        raise ValueError('method must be "number" or "value"')

    source = alt.Data(values=countries)

    if ranking.plot_type == 'indicator_vs_temperature':
        details = 'warming level: {} {}'.format(x, ranking.plot_unit_x)
    else:
        details = 'period: {}, scenario: {}'.format(
            x, {
                'rcp26': 'RCP 2.6',
                'rcp45': 'RCP 4.5',
                'rcp60': 'RCP 6',
                'rcp85': 'RCP 8.5'
            }.get(scenario, scenario))
    default_title = getattr(ranking, 'plot_label_y', '') + '\n' + details
    # default_label = 'ranking number' if method == 'number' else ('ranking value ({})'.format(getattr(ranking, 'plot_unit_y')))

    ranking_data = get_ranking_data(countries, ranking, x, scenario, method)

    chart = alt.Chart(source).mark_geoshape().encode(
        # color="Rank:Q",
        color=alt.Color("Rank:Q", sort='ascending')
        if method == 'number' else alt.Color("Value:Q", sort='descending'),
        # tooltip=["Country:N", "Code:N", "Value:Q", "Rank:Q"]
        tooltip=[
            "label:N", "unit:N", "Country:N", "Code:N", "Value:Q", "Rank:Q"
        ]).transform_lookup(lookup='properties.ISIPEDIA',
                            from_=alt.LookupData(ranking_data, 'Code',
                                                 ranking_data.columns.tolist())
                            ).project('naturalEarth1').properties(
                                width=800,
                                autosize=alt.AutoSizeParams(contains="padding",
                                                            type="fit-x"),
                                title=ranking.plot_title
                                # ).configure_view(stroke=None
                            ).configure(background='#F1F4F4').configure_title(
                                fontSize=16, ).configure_axis(
                                    labelFontSize=14,
                                    titleFontSize=16,
                                ).configure_legend(
                                    titleFontSize=14,
                                    labelFontSize=14,
                                ).configure_mark(fontSize=14)
    # ).interactive()

    return chart
Exemple #21
0
def generate_regions_choropleth(
    data: pd.DataFrame,
    feature: str,
    title: str,
    width: int = 700,
    height: int = 1000,
    log_scale: bool = True,
    is_region: bool = True,
) -> alt.Chart:
    if is_region:
        shape = alt.topo_feature(
            "https://raw.githubusercontent.com/openpolis/geojson-italy/master/topojson/limits_IT_regions.topo.json",
            "regions",
        )
    else:
        shape = alt.topo_feature(
            "https://raw.githubusercontent.com/openpolis/geojson-italy/master/topojson/limits_IT_provinces.topo.json",
            "provinces",
        )

    area_name = "reg_name" if is_region else "prov_name"
    lookup_in_shape = "reg_istat_code_num" if is_region else "prov_istat_code_num"
    lookup_in_df = "codice_regione" if is_region else "codice_provincia"

    chart_data = data[data[feature] > 0][[feature, lookup_in_df]]

    base_chart = (alt.Chart(shape).mark_geoshape(
        stroke="black", strokeWidth=0.5, color="white").encode(
            tooltip=[alt.Tooltip(f"properties.{area_name}:N", title=title)]))
    scale = (alt.Scale(type="log", scheme="teals")
             if log_scale else alt.Scale(type="linear", scheme="teals"))
    color_chart = (alt.Chart(shape).mark_geoshape(
        stroke="black", strokeWidth=0.5).encode(
            color=alt.Color(
                f"{feature}:Q",
                title=formatter(feature),
                scale=scale,
                legend=alt.Legend(labelLimit=50),
            ),
            tooltip=[
                alt.Tooltip(f"properties.{area_name}:N", title=title),
                alt.Tooltip(f"{feature}:Q",
                            title=formatter(feature),
                            format=".4~f"),
            ],
        ).transform_lookup(
            f"properties.{lookup_in_shape}",
            from_=alt.LookupData(
                data=chart_data,
                key=lookup_in_df,
                fields=[feature],
            ),
        ))

    final_chart = ((base_chart + color_chart).configure_view(
        strokeWidth=0).properties(width=width, height=height))

    return final_chart
Exemple #22
0
    def initialize_chart(self):
        x_attr = self.vis.get_attr_by_channel("x")[0]
        y_attr = self.vis.get_attr_by_channel("y")[0]

        x_attr_abv = str(x_attr.attribute)
        y_attr_abv = str(y_attr.attribute)

        background, background_str = self.get_background(x_attr_abv.lower())
        geographical_name = self.get_geographical_name(x_attr_abv.lower())
        geo_map, geo_map_str, map_type, map_translation = self.get_geomap(
            x_attr_abv.lower())
        self.data[x_attr_abv] = self.data[x_attr_abv].apply(map_translation)

        if len(x_attr_abv) > 25:
            x_attr_abv = x_attr.attribute[:15] + "..." + x_attr.attribute[-10:]
        if len(y_attr_abv) > 25:
            y_attr_abv = y_attr.attribute[:15] + "..." + y_attr.attribute[-10:]

        if isinstance(x_attr.attribute, str):
            x_attr.attribute = x_attr.attribute.replace(".", "")
        if isinstance(y_attr.attribute, str):
            y_attr.attribute = y_attr.attribute.replace(".", "")

        self.data = AltairChart.sanitize_dataframe(self.data)

        points = (alt.Chart(geo_map).mark_geoshape().encode(
            color=f"{str(y_attr.attribute)}:Q", ).transform_lookup(
                lookup="id",
                from_=alt.LookupData(self.data, str(x_attr.attribute),
                                     [str(y_attr.attribute)]),
            ).project(type=map_type).properties(
                title=f"Mean of {y_attr_abv} across {geographical_name}"))

        chart = background + points

        ######################################
        ## Constructing Altair Code String ##
        #####################################

        self.code += "import altair as alt\n"
        dfname = "placeholder_variable"
        self.code += f"""nan=float('nan')
df = pd.DataFrame({str(self.data.to_dict())})
background = {background_str}

		points = alt.Chart({geo_map_str}).mark_geoshape().encode(
    color='{str(y_attr.attribute)}:Q',
).transform_lookup(
    lookup='id',
    from_=alt.LookupData({dfname}, "{str(x_attr.attribute)}", ["{str(y_attr.attribute)}"])
).project(
    type="{map_type}"
).properties(
    title="Mean of {y_attr_abv} across {geographical_name}"
)
chart = background + points
		"""
        return chart
Exemple #23
0
def get_demographic_country(df):

    df2 = df.copy()
    df2.Country = df2.Country.fillna('<MISSING>')
    df2 = pd.DataFrame(df2.groupby(by=['ROWID','Country']).size()\
        .reset_index()[['ROWID','Country']].Country.value_counts(dropna=False))\
        .reset_index().rename(columns={'index':'country', 'Country':'count'}).sort_values(by='country')

    ctry = pd.DataFrame({
        'country': [
            '<MISSING>', 'Afghanistan', 'Canada', 'China', 'France',
            'Hong Kong (S.A.R.)', 'India', 'Italy', 'Mexico', 'New Zealand',
            'Portugal', 'Singapore',
            'United Kingdom of Great Britain and Northern Ireland',
            'United States of America'
        ],
        'id':
        [0, 4, 124, 156, 250, 344, 356, 380, 484, 554, 620, 702, 826, 840]
    })

    df2 = df2.merge(ctry, how='inner', on='country')

    source = alt.topo_feature(data.world_110m.url, "countries")
    background = alt.Chart(source).mark_geoshape(fill="white")

    foreground = (alt.Chart(source).mark_geoshape(
        stroke=berkeley_palette['bay_fog'], strokeWidth=0.25).encode(
            color=alt.Color(
                "count:N",
                scale=alt.Scale(range=[
                    berkeley_palette['pacific'], berkeley_palette['lawrence'],
                    berkeley_palette['lap_lane'],
                    berkeley_palette['founders_rock'],
                    berkeley_palette['founders_rock'],
                    berkeley_palette['berkeley_blue']
                ]),
                legend=None,
            ),
            tooltip=[
                alt.Tooltip("country:N", title="Country"),
                alt.Tooltip("count:Q", title="Participants"),
            ],
        ).transform_lookup(
            lookup="id",
            from_=alt.LookupData(df2, "id", ["count", "country"]),
        ))

    final_map = alt.layer(background, foreground)\
        .properties(width=700, height=400, title={'text':'Distribution of Country'})\
        .configure_title(anchor='middle')\
        .configure_title(dy=-10)\
        .project("naturalEarth1")\
        .configure(padding={'top':20, 'left':20, 'right':20,'bottom':20})\
        .configure_view(stroke=None, strokeWidth=0)\
        .configure_axis(grid=False)

    return final_map
Exemple #24
0
def map_state(curr_day_num, state_txt, state_counties, confirmed,
              confirmed_min, confirmed_max, deaths, deaths_min, deaths_max):
    # Washington State
    base_state = alt.Chart(state_counties).mark_geoshape(
        fill='white',
        stroke='lightgray',
    ).properties(
        width=1000,
        height=800,
    ).project(type='mercator')

    # counties
    base_state_counties = alt.Chart(
        us_counties).mark_geoshape().transform_lookup(
            lookup='id',
            from_=alt.LookupData(
                confirmed[(confirmed['confirmed'] > 0)
                          & (confirmed['day_num'] == curr_day_num)], 'fips',
                ['confirmed', 'county'])).encode(
                    color=alt.Color('confirmed:Q',
                                    scale=alt.Scale(
                                        type='log',
                                        domain=[confirmed_min, confirmed_max]),
                                    title='Confirmed'),
                    tooltip=[
                        alt.Tooltip('confirmed:Q'),
                        alt.Tooltip('county:O'),
                    ],
                )

    # deaths by long, latitude
    points = alt.Chart(
        deaths[(deaths['deaths'] > 0) & (deaths['day_num'] == curr_day_num)]
    ).mark_point(opacity=0.75, filled=True).encode(
        longitude='long_:Q',
        latitude='lat:Q',
        size=alt.Size('sum(deaths):Q',
                      scale=alt.Scale(type='symlog',
                                      domain=[deaths_min, deaths_max]),
                      title='deaths'),
        color=alt.value('#BD595D'),
        stroke=alt.value('brown'),
        tooltip=[
            alt.Tooltip('lat'),
            alt.Tooltip('long_'),
            alt.Tooltip('deaths'),
            alt.Tooltip('county:O'),
        ],
    ).properties(
        # update figure title
        title=
        f'COVID-19 {state_txt} Confirmed Cases and Deaths per 100K by County [{curr_day_num}]'
    )

    return (base_state + base_state_counties + points)
def plot_norway():
    """Creates a plot displaying the reported COVID-19 rate per 100000 
        inhabitants by county in Norway.
    
    The data was last updated 11.11.2020.

    Returns:
        altair.vegalite.v4.api.Chart: The plotted chart.
    """
    data = pd.read_csv("antall-meldte-tilfeller.csv", sep=";")

    # topojson of norways counties
    counties = alt.topo_feature(
        "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/norway/norway-new-counties.json",
        "Fylker")

    # Used for highlighting
    nearest = alt.selection(type="single",
                            on="mouseover",
                            fields=["properties.navn"],
                            empty="none")

    fig = alt.Chart(counties).mark_geoshape().encode(
        tooltip=[
            alt.Tooltip("properties.navn:N", title="Fylke"),
            alt.Tooltip("Insidens:Q", title="Tilfeller per 100 000"),
        ],
        color=alt.Color("Insidens:Q",
                        scale=alt.Scale(scheme="reds"),
                        legend=alt.Legend(title="Tilfeller per 100 000",
                                          direction="horizontal",
                                          orient="bottom",
                                          gradientLength=375)),
        stroke=alt.condition(nearest, alt.value("grey"), alt.value(None)),
        opacity=alt.condition(nearest, alt.value(1), alt.value(0.8)),

        # Map cases to counties
    ).transform_lookup(
        lookup="properties.navn",
        from_=alt.LookupData(data, "Category", ["Insidens"])).properties(
            width=375,
            height=450,
            title={
                "text":
                "Antall tilfeller per 100 000 innbyggere i hvert fylke",
                "subtitle": "Oppdatert 11.11.2020",
                "subtitleColor": "lightgray"
            }).add_selection(nearest).configure_view(
                strokeOpacity=0  #  Removes borders
            )

    return fig
Exemple #26
0
def get_demographic_state(df):

    df2 = df.copy()
    df2.State = df2.State.fillna('<MISSING>')
    df2 = pd.DataFrame(df2.groupby(by=['ROWID','State']).size()\
        .reset_index()[['ROWID','State']].State.value_counts(dropna=False))\
        .reset_index().rename(columns={'index':'state', 'State':'count'}).sort_values(by='state')

    codes = pd.DataFrame({
        'state': [
            'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
            'Colorado', 'Connecticut', 'Delaware', 'District of Columbia',
            'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana',
            'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland',
            'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
            'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
            'New Jersey', 'New Mexico', 'New York', 'North Carolina',
            'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
            'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee',
            'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington',
            'West Virginia', 'Wisconsin', 'Wyoming', 'Puerto Rico'
        ],
        'id': [
            1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21,
            22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
            39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 72
        ]
    })

    df2 = df2.merge(codes, how='left', on='state').fillna(-99)
    df2.id = df2.id.astype(int)

    states = alt.topo_feature(data.us_10m.url, 'states')
    b = alt.Chart(states).mark_geoshape(stroke=berkeley_palette['white'], strokeWidth=0.25).encode(
            color=alt.Color(
                "count:N", scale=alt.Scale(range=[berkeley_palette['pacific'], "#00b0da",
                "#009dcb", "#008aba", "#0077aa", "#006598", "#005386", "#004274", "#003262"]), legend=None),
            tooltip=[
                alt.Tooltip("state:N", title="U.S. State"),
                alt.Tooltip("count:Q", title="Participants")]
        ).transform_lookup(
            lookup='id',
            from_=alt.LookupData(df2, 'id', ["count","state"]))\
        .project(type='albersUsa')\
        .properties(width=700, height=400, title={'text':'Distribution of U.S. State'})\
        .configure_title(anchor='middle')\
        .configure_title(dy=-10)\
        .configure(padding={'top':20, 'left':20, 'right':20,'bottom':20})\
        .configure_view(stroke=None, strokeWidth=0)\
        .configure_axis(grid=False)

    return b
Exemple #27
0
def plot_map(df, state_id=6):
    """
    Plot a Choropleth map of US States and Wine Reviews.

    Parameters:
    -----------
    df -- (pandas DataFrame) Cleaned data in a dataframe.
    state_id -- (int) Integer of state_id (ex. 6 for 'California)

    Returns altiar plot objects.
    """

    wine_counties = wrangle_counties(df)
    counties = alt.topo_feature(data.us_10m.url, 'counties')

    state = lookup_state_id(df, state_id)
    state_id = state['state_id']

    colormap = alt.Scale(domain=[0, 100, 500, 1000, 2000, 4000, 8000],
                         range=[
                             '#C7DBEA', '#CCCCFF', '#B8AED2', '#3A41C61',
                             '#9980D4', '#4634A7', '#4C2C96'
                         ])

    c_foreground = (alt.Chart(counties).mark_geoshape(
        stroke='black', strokeWidth=1).encode(
            color=alt.Color('Num Reviews:Q', scale=colormap),
            tooltip=[
                alt.Tooltip('County:O'),
                alt.Tooltip('Ave Rating:Q', format='.2f'),
                alt.Tooltip('Ave Price:Q', format='$.2f'),
                alt.Tooltip('Ave Value:Q', format='.2f'),
                alt.Tooltip('Num Reviews:Q')
            ]).transform_calculate(
                state_id="(datum.id / 1000)|0").transform_filter(
                    (alt.datum.state_id) == state_id).transform_lookup(
                        lookup='id',
                        from_=alt.LookupData(wine_counties, 'County ID', [
                            'County', 'County ID', 'Ave Rating', 'Ave Price',
                            'Ave Value', 'Num Reviews'
                        ])))

    c_background = (alt.Chart(counties).mark_geoshape(
        fill='dimgray', stroke='gray').transform_calculate(
            state_id="(datum.id / 1000)|0").transform_filter(
                (alt.datum.state_id) == state_id)).project('albersUsa')

    return (c_background + c_foreground).configure_view(height=400,
                                                        width=240,
                                                        strokeWidth=4,
                                                        fill=None,
                                                        stroke=None)
Exemple #28
0
def plot_norway():
    """
    Plots number of cases per 100k on each county on a chart depicting Norway.

    Returns:
        jsonDict(dict): plot json structure in dictionary

    """
    #get directory
    currentDir = pathlib.Path(__file__).parent.absolute()
    countyDir = str(currentDir) + "/covcounties/"
    os.chdir(countyDir)
    #create dataframe from county csv file
    data = pd.read_csv(countyDir + "reported-county.csv")
    #extract counties from json file
    counties = alt.topo_feature(
        "https://raw.githubusercontent.com/deldersveld/topojson/master/countries/norway/norway-new-counties.json",
        "Fylker")
    #nearest selection of county
    nearest = alt.selection(type="single",
                            on="mouseover",
                            fields=["properties.navn"],
                            empty="none")
    #plot country chart
    country_chart = alt.Chart(counties).mark_geoshape().encode(
        #hover effect
        tooltip=[
            alt.Tooltip("properties.navn:N", title="Fylke"),
            alt.Tooltip("Insidens:Q", title="Antall meldte tilfeller per 100k")
        ],
        color=alt.Color(
            "Insidens:Q",
            scale=alt.Scale(scheme="reds"),
            legend=alt.Legend(title="Antall meldte tilfeller per 100k")),
        stroke=alt.condition(nearest, alt.value("gray"), alt.value(None)),
        opacity=alt.condition(nearest, alt.value(1), alt.value(0.8)),
        #lookup number of cases from dataframe and map it to counties
    ).transform_lookup(
        lookup="properties.navn",
        from_=alt.LookupData(data, "Category", ["Insidens"])).properties(
            width=500,
            height=600,
            title="Antall meldte tilfeller per 100k i hvert fylke"
        ).add_selection(nearest)

    #Save to file and return json string
    json = country_chart.to_json()

    #Fix json translation of null to None
    #jsonDict['encoding']['stroke']['value'] = "null"

    return json
Exemple #29
0
def base_layers(node_data, edge_data):
    x, y = alt.X('x:Q', axis=None), alt.Y('y:Q', axis=None)
    lookup = alt.LookupData(data=node_data, key='node_id', fields=['x', 'y'])

    node_base = alt.Chart(node_data).encode(x=x, y=y)
    edge_base = (
        alt.Chart(edge_data).encode(
            x=x, y=y, detail='edge_id')  # `detail` for one line per edge
        .transform_lookup(
            lookup='node_id',
            from_=lookup,
        ))
    return node_base, edge_base
Exemple #30
0
def kaart_plot(cn6_x):
    # Title
    st.subheader("International trade flows to and from Europe in 2019")
    x = pd.read_csv('data/edges_puhastus2019.csv', sep=';')
    x = x.loc[:, ~x.columns.str.contains('^Unnamed')]
    x = remap_cn6(x)
    countries = pd.read_csv('countries.csv', sep=';')
    world = alt.topo_feature(data.world_110m.url, 'countries')
    x = x[x["cn6"] == cn6_x]
    conns = x
    select_country = alt.selection_single(on="mouseover",
                                          nearest=True,
                                          fields=["origin"],
                                          empty="none")
    lookup_data = alt.LookupData(countries,
                                 key="country",
                                 fields=["name", "latitude", "longitude"])
    background = alt.Chart(world).mark_geoshape(
        fill="lightgray",
        stroke="white").properties(width=1000,
                                   height=800).project(type='naturalEarth1')
    connections = alt.Chart(conns).mark_rule(opacity=0.35).encode(
        latitude="latitude:Q",
        longitude="longitude:Q",
        latitude2="lat2:Q",
        longitude2="lon2:Q").transform_lookup(
            lookup="origin", from_=lookup_data).transform_lookup(
                lookup="destination",
                from_=lookup_data,
                as_=["country", "lat2",
                     "lon2"]).transform_filter(select_country)
    points = alt.Chart(conns).mark_circle().encode(
        latitude="latitude:Q",
        longitude="longitude:Q",
        size=alt.Size("connections:Q",
                      scale=alt.Scale(range=[0, 400]),
                      legend=None),
        order=alt.Order("connections:Q", sort="descending"),
        tooltip=["origin:N", "connections:Q"]).transform_aggregate(
            connections="count()", groupby=["origin"]).transform_lookup(
                lookup="origin",
                from_=lookup_data).add_selection(select_country)
    st.altair_chart((background + connections +
                     points).configure_view(stroke=None).resolve_scale())
    # Description
    st.markdown("""
    International trade flows to and from EU in 2019. The size of the country node shows
    the number of trade flows to and from other countries. Data: 
    [Comext](https://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?sort=1&dir=comext) yearly data.
                """)