Exemple #1
0
def s_avg_graph():
    df_solar_world = load_data_world_s()
    brush = alt.selection(type='interval', encodings=['x'])

    bars = alt.Chart().mark_bar().encode(
        alt.X('Year', scale=alt.Scale(zero=False)),
        y='mean(Solar_LCOE (2019 USD/kWh))',
        opacity=alt.condition(brush, alt.OpacityValue(1),
                              alt.OpacityValue(0.7)),
    ).add_selection(brush).properties(
        title='Utility-scale solar PV weighted average cost of electricity',
        width=700,
        height=350)

    line = alt.Chart().mark_rule(color='firebrick').encode(
        y='mean(Solar_LCOE (2019 USD/kWh))',
        size=alt.SizeValue(3),
        tooltip=["mean(Solar_LCOE (2019 USD/kWh))"]).transform_filter(brush)

    country = st.selectbox("Select country", [
        "Australia", "China", "France", "Germany", "India", "Italy", "Japan",
        "Netherlands", "Republic of Korea", "Spain", "Turkey", "Ukraine",
        "United Kingdom", "United States", "Vietnam"
    ])
    xyz = alt.layer(bars,
                    line,
                    data=df_solar_world[df_solar_world["Country"] == country])
    st.altair_chart(xyz)
Exemple #2
0
def w_inst_graph():
    df_wind_world = load_data_world_w()
    brush = alt.selection(type='interval', encodings=['x'])

    bars = alt.Chart().mark_bar().encode(
        alt.X('Year', scale=alt.Scale(zero=False)),
        y='mean(Total installed costs (2019 USD/kW))',
        opacity=alt.condition(brush, alt.OpacityValue(1),
                              alt.OpacityValue(0.7)),
    ).add_selection(brush).properties(
        title='Utility-scale solar PV weighted average cost of electricity',
        width=700,
        height=350)

    line = alt.Chart().mark_rule(color='firebrick').encode(
        y='mean(Total installed costs (2019 USD/kW))',
        size=alt.SizeValue(3),
        tooltip=["mean(Total installed costs (2019 USD/kW))"
                 ]).transform_filter(brush)

    country = st.selectbox("Select country", [
        "Brazil", "Canada", "China", "Denmark", "France", "Germany", "India",
        "Italy", "Japan", "Mexico", "Spain", "Sweden", "Turkey",
        "United Kingdom", "United States"
    ])
    xyz = alt.layer(bars,
                    line,
                    data=df_wind_world[df_wind_world["Country"] == country])
    st.altair_chart(xyz)
Exemple #3
0
    def returned_users_chart(self):
        df = self.returned_users_data()
        brush = alt.selection(type='interval', encodings=['x'])
        bars = alt.Chart().mark_bar().encode(
            x='monthdate(dates):O',
            y=alt.Y('Count:Q', scale=alt.Scale(domain=[0, 2])),
            opacity=alt.condition(brush, alt.OpacityValue(1),
                                  alt.OpacityValue(0.7)),
        ).add_selection(brush)

        line = alt.Chart().mark_rule(color='firebrick').encode(
            y='mean(Count):Q', size=alt.SizeValue(3)).transform_filter(brush)

        returned_users = alt.layer(bars, line, data=df).properties(height=300,
                                                                   width=500)

        return returned_users
def draw_major_statistics(df, selected, useful_cols):
    # first visualization #
    st.markdown("""
    ## Let's explore various statistics of all majors!

    #### Instructions for use:
    - From the sidebar on the left, you can narrow down the major categories as you wish, by selecting / deselecting them to interact with filtered data
    - You can choose a field to view the statistics of all majors
    - The red line on the graph indicates the average value of all majors
    - You can also select a range of specific majors to measure the average value of of the statistics
    """)

    filtered_df = df.loc[df["Major_category"].isin(selected)]

    # select box #
    option_field = rev_explanations[st.selectbox('Choose a field!',
                                                 useful_cols)]

    avg_brush = alt.selection(type='interval', encodings=['y'])

    chart = alt.Chart(filtered_df).mark_bar().encode(
        x=alt.X(
            option_field,
            scale=alt.Scale(zero=False),
        ),
        y=alt.Y("Major",
                scale=alt.Scale(zero=False),
                sort='-x',
                axis=alt.Axis(labelOverlap=True)),
        color=alt.Y("Major_category"),
        opacity=alt.condition(avg_brush, alt.OpacityValue(1),
                              alt.OpacityValue(0.4)),
        tooltip=["Major", "Major_category",
                 option_field]).add_selection(avg_brush).properties(width=1000,
                                                                    height=750)

    avg_line = alt.Chart(filtered_df).mark_rule(color='firebrick').encode(
        x='mean(' + option_field + '):Q',
        size=alt.SizeValue(3)).transform_filter(avg_brush).properties(
            width=1000, height=750)

    visual_1 = alt.layer(chart, avg_line)

    st.write(visual_1)
def make_chart(src):
    brush = alt.selection(type="interval", encodings=["x", "y"])
    color = alt.Color("y:O", legend=None)

    line = (alt.Chart(src).mark_line(interpolate="natural",
                                     color="lightblue",
                                     size=2).encode(x=alt.X("x", title="Days"),
                                                    y=alt.Y(
                                                        "y",
                                                        title="Flowrate cfs")))

    points = (alt.Chart(src).mark_point().encode(
        x="x",
        y="y",
        color=alt.condition(brush, color, alt.value("lightgray")),
        tooltip=[
            alt.Tooltip("y:Q", format=".2f", title="Flowrate"),
            alt.Tooltip("x:Q", format=".1f", title="Day"),
        ],
    ).add_selection(brush))

    avg_line = (alt.Chart(src).mark_rule(color="grey", opacity=0.5).encode(
        y="mean(y):Q",
        size=alt.SizeValue(3),
    ).transform_filter(brush))

    fit_line = line.transform_regression("x", "y").mark_line(color="firebrick")

    text = (alt.Chart(src).mark_text(
        align="left",
        baseline="middle",
        x="width",
        dx=7,
    ).encode(y="mean(y):Q",
             text=alt.Text("mean(y):Q", format=".2f")).transform_filter(brush))

    return avg_line + line + points + fit_line + text
def display_main_chart(metrics_df,
                       metric_id,
                       metric_name,
                       asset_names,
                       container,
                       scale="linear"):
    # the selection brush oriented on the x-axis
    # important not here had to comment out the interactive function below
    # to convert the graph to static
    brush = alt.selection(type='interval', encodings=['x'])
    base = alt.Chart(metrics_df).properties(width=800)
    chart = base.mark_line().encode(x=alt.X("time",
                                            type="temporal",
                                            title="Time"),
                                    y=alt.Y(metric_id,
                                            type="quantitative",
                                            title=metric_name,
                                            scale=alt.Scale(type=scale),
                                            stack=True),
                                    opacity=alt.condition(
                                        brush, alt.OpacityValue(1),
                                        alt.OpacityValue(0.7)),
                                    tooltip=[
                                        alt.Tooltip("time",
                                                    type="temporal",
                                                    title="Time"),
                                        alt.Tooltip(metric_id,
                                                    type="quantitative",
                                                    title=metric_name)
                                    ],
                                    color="Name").add_selection(brush)
    line = base.mark_rule().encode(y=alt.Y(f"average({metric_id}):Q"),
                                   size=alt.SizeValue(3),
                                   color="Name").transform_filter(brush)

    container.write(chart + line)
Exemple #7
0
def home():

    ### BEHROOZ
    # read volume file and assign to vol data frame
    volume_file = ('static/Volumes')
    vol = pd.read_csv(volume_file, delim_whitespace=True)

    # GRVQHC
    # For GRV vs GRV quantiles by HC Column charts
    brush = alt.selection(type='interval')

    points = alt.Chart(vol).mark_point().encode(
        x='Oil_GRV_10_6:Q',
        y='Oil_GRV_quantile:Q',
        tooltip=['Num', 'Oil_GRV_quantile'],
        color=alt.condition(brush, 'Hc_column__m_:Q',
                            alt.value('darkgray'))).add_selection(brush)

    bars = alt.Chart().mark_bar().encode(
        alt.Color('Hc_column__m_:Q', scale=alt.Scale(scheme='viridis')),
        y='Hc_column__m_:Q',
        x='Oil_GRV_10_6:Q').transform_filter(brush)

    GRVQHC = alt.vconcat(points, bars, data=vol)
    GRVQHC = GRVQHC.to_json()

    # GRVOWC
    brush = alt.selection(type='interval')

    points = alt.Chart(vol).mark_point().encode(
        alt.X('Oil_GRV_10_6:Q'),
        alt.Y('OWC_depth:Q', scale=alt.Scale(zero=False)),
        tooltip=['Num', 'Oil_GRV_quantile'],
        color=alt.condition(brush, 'Oil_GRV_quantile:Q',
                            alt.value('darkgray'))).add_selection(brush)

    bars = alt.Chart().mark_bar().encode(
        alt.Color('Oil_GRV_quantile:Q', scale=alt.Scale(scheme='viridis')),
        y='Hc_column__m_:Q',
        x='Oil_GRV_10_6:Q').transform_filter(brush)

    GRVOWC = alt.vconcat(points, bars, data=vol)
    GRVOWC = GRVOWC.to_json()

    # GRVDNS
    # For the histogram of GRV density with Min,Mean,Max HC column indicators

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

    bars = alt.Chart(vol).mark_bar().encode(
        alt.X("GRV_density__m_:Q", bin=alt.Bin(maxbins=20)),
        alt.Y('count()', axis=alt.Axis(title='Min,Mean,Max HC')),
        opacity=alt.condition(
            brush, alt.OpacityValue(1),
            alt.OpacityValue(0.7))).add_selection(brush).properties(width=600,
                                                                    height=400)

    line1 = alt.Chart(vol).mark_rule(color='firebrick').encode(
        y='max(Hc_column__m_):Q',
        size=alt.SizeValue(2)).transform_filter(brush)

    line2 = alt.Chart(vol).mark_rule(color='yellow').encode(
        y='min(Hc_column__m_):Q',
        size=alt.SizeValue(2)).transform_filter(brush)

    line3 = alt.Chart(vol).mark_rule(color='green').encode(
        y='mean(Hc_column__m_):Q',
        size=alt.SizeValue(2)).transform_filter(brush)

    GRVDNS = alt.layer(bars, line1, line2, line3, data=vol)
    GRVDNS = GRVDNS.to_json()

    return render_template('index.html',
                           GRVQHC=GRVQHC,
                           GRVOWC=GRVOWC,
                           GRVDNS=GRVDNS)
Exemple #8
0
"""
Locations of US Airports
========================
This is a layered geographic visualization that shows the positions of US
airports on a background of US states.
"""
# category: geographic
import altair as alt
from vega_datasets import data

states = alt.UrlData(data.us_10m.url,
                     format=alt.TopoDataFormat(type='topojson',
                                               feature='states'))
airports = data.airports.url

# US states background
background = alt.Chart(states).mark_geoshape(
    fill='lightgray',
    stroke='white').properties(projection={'type': 'albersUsa'},
                               width=500,
                               height=300)

# airport positions on background
points = alt.Chart(airports).mark_circle().encode(alt.X('longitude:lon'),
                                                  alt.Y('latitude:lat'),
                                                  alt.SizeValue(10),
                                                  alt.ColorValue('steelblue'))

chart = background + points
filter_genres = base.add_selection(genre_select).transform_filter(
    genre_select).properties(title="Dropdown Filtering")

#color changing marks
rating_radio = alt.binding_radio(options=ratings)

rating_select = alt.selection_single(fields=['MPAA_Rating'],
                                     bind=rating_radio,
                                     name="Rating")
rating_color_condition = alt.condition(rating_select,
                                       alt.Color('MPAA_Rating:N', legend=None),
                                       alt.value('lightgray'))

highlight_ratings = base.add_selection(rating_select).encode(
    color=rating_color_condition).properties(title="Radio Button Highlighting")

# Boolean selection for format changes
input_checkbox = alt.binding_checkbox()
checkbox_selection = alt.selection_single(bind=input_checkbox,
                                          name="Big Budget Films")

size_checkbox_condition = alt.condition(
    checkbox_selection, alt.SizeValue(25),
    alt.Size('Hundred_Million_Production:Q'))

budget_sizing = base.add_selection(checkbox_selection).encode(
    size=size_checkbox_condition).properties(title="Checkbox Formatting")

(filter_year | filter_genres) & (highlight_ratings | budget_sizing).show()
Exemple #10
0
bars = alt.Chart().mark_bar().encode(
    alt.Color('Oil_GRV_quantile:Q', scale=alt.Scale(scheme='viridis')),
    y='Hc_column__m_:Q',
    x='Oil_GRV_10_6:Q').transform_filter(brush)

GRVOWC = alt.vconcat(points, bars, data=vol)
GRVOWC.to_json()

# For the histogram of GRV density with Min,Mean,Max HC column indicators

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

bars = alt.Chart(vol).mark_bar().encode(
    alt.X("GRV_density__m_:Q", bin=alt.Bin(maxbins=20)),
    alt.Y('count()', axis=alt.Axis(title='Min,Mean,Max HC')),
    opacity=alt.condition(
        brush, alt.OpacityValue(1),
        alt.OpacityValue(0.7))).add_selection(brush).properties(width=600,
                                                                height=400)

line1 = alt.Chart(vol).mark_rule(color='firebrick').encode(
    y='max(Hc_column__m_):Q', size=alt.SizeValue(2)).transform_filter(brush)

line2 = alt.Chart(vol).mark_rule(color='yellow').encode(
    y='min(Hc_column__m_):Q', size=alt.SizeValue(2)).transform_filter(brush)

line3 = alt.Chart(vol).mark_rule(color='green').encode(
    y='mean(Hc_column__m_):Q', size=alt.SizeValue(2)).transform_filter(brush)

GRVDNS = alt.layer(bars, line1, line2, line3, data=vol)
GRVDNS.to_json()
def uv_histPlot(data, engine, xlabel, ylabel):
    data = data.copy()
    data.rename(columns={'plotX1': ylabel}, inplace=True)

    if engine == 'Static':
        fig, axes = plt.subplots(figsize=(9.4, 5))
        data[ylabel].hist(ax=axes)

        axes.set_xlabel(xlabel, fontsize=15)
        axes.set_ylabel(ylabel, fontsize=15)
        axes.grid(b=True, which='major', color='k', linewidth=0.25)
        axes.grid(b=True, which='minor', color='k', linewidth=0.125)

        plt.close()
        return pn.pane.Matplotlib(fig, tight=True)

    elif engine == 'Interactive':

        brush = alt.selection(type='interval', encodings=['x'])
        source = data[ylabel].reset_index()
        base = alt.Chart(source).mark_bar()
        if any(data[ylabel].dropna() < 0):
            base = base.transform_calculate(
                negative='datum.{0} < 0'.format(ylabel))
            base = base.encode(x=alt.X('{0}:T'.format(data.index.name)),
                               y=alt.Y('{0}:Q'.format(ylabel),
                                       axis=alt.Axis(format='~s')),
                               tooltip=ylabel,
                               color=alt.Color('negative:N', legend=None))
        else:
            base = base.encode(x=alt.X('{0}:T'.format(data.index.name)),
                               y=alt.Y('{0}:Q'.format(ylabel),
                                       axis=alt.Axis(format='~s')),
                               tooltip=ylabel)
        base = base.properties(width=600, height=320)

        upper = base.encode(
            alt.X('{0}:T'.format(data.index.name),
                  scale=alt.Scale(domain=brush)))
        upper.configure_title(fontSize=25)
        upper.encoding.x.title = ''
        upper.encoding.y.title = ylabel
        upper.configure_axisBottom(labelFontSize=15)
        upper.configure_axisLeft(labelFontSize=15)

        lower = base.properties(height=30).add_selection(brush)
        lower.title = ''
        lower.encoding.x.title = 'Interval Selection'
        lower.encoding.y.title = ''
        lower.encoding.y.axis.title = ''
        lower.configure_axisBottom(labelFontSize=4)
        lower.configure_axisLeft(labelFontSize=1)

        line = alt.Chart()
        line = line.mark_rule(color='firebrick')
        line = line.encode(y='mean({0}):Q'.format(ylabel),
                           size=alt.SizeValue(3))
        line = line.transform_filter(brush)
        upper = alt.layer(upper, line, data=source)

        p = alt.vconcat(upper, lower).configure_concat(spacing=2)
        return p
Exemple #12
0
def jitter_summary_chart(
    norm_error,
    author=None,
    title=None,
    sort_list=None,
    opacity=False,
    color_scheme="category10",
):
    source = norm_error.to_dataframe().reset_index()
    if type(author) == list:
        source = source.query(f"author not in @author")
    elif type(author) == str:
        source = source.query(f"author != '{author}'")

    selector = alt.selection_single(empty="none", fields=["sample_id"])
    if opacity:
        opacity = alt.condition(selector, alt.OpacityValue(1.0),
                                alt.OpacityValue(0.5))
    else:
        opacity = alt.OpacityValue(1.0)

    size = alt.condition(selector, alt.SizeValue(150), alt.SizeValue(60))

    # modify that for changes in coloring. Make sure that domain is correct
    domain, range_ = _get_colors()

    stripplot = (
        alt.Chart(source, width=100, height=600).mark_circle().encode(
            x=alt.X(
                "jitter:Q",
                title=None,
                axis=alt.Axis(values=[0], ticks=True, grid=False,
                              labels=False),
                scale=alt.Scale(),
            ),
            y=alt.Y("normalized_error:Q", title="Normalized error"),
            color=alt.Color("author:N",
                            legend=None,
                            scale=alt.Scale(domain=domain, range=range_)),
            column=alt.Column(
                "author:N",
                header=alt.Header(
                    labelAngle=-90,
                    titleOrient="top",
                    labelOrient="bottom",
                    labelAlign="right",
                    labelPadding=3,
                    labelFontSize=20,
                    title=title,
                ),
                sort=sort_list,
            ),
            size=size,
            opacity=opacity,
            tooltip=["author", "sample_id", "normalized_error"],
        ).transform_calculate(
            # Generate Gaussian jitter with a Box-Muller transform
            jitter="sqrt(-2*log(random()))*cos(2*PI*random())").
        configure_facet(spacing=5).configure_view(stroke=None).add_selection(
            selector).transform_filter("datum.normalized_error !== null"))

    return stripplot.configure_axis(
        labelFontSize=20, titleFontSize=20).configure_header(titleFontSize=24)
"""
Line Chart with Layered Aggregates
----------------------------------
This example shows how to make a multi series line chart of the daily closing
stock prices for AAPL, AMZN, GOOG, IBM, and MSFT between 2000 and 2010, along
with a layered rule showing the average values.
"""

import altair as alt
from vega_datasets import data

stocks = data.stocks()

line = alt.Chart(stocks).mark_line().encode(
    x='date', y='price', color='symbol').properties(
        width=600,
        title="Daily closing prices with their aggregate prices").interactive(
            bind_y=False)

rule = alt.Chart(stocks).mark_rule().encode(y=alt.Y('average(price)', ),
                                            color='symbol',
                                            size=alt.SizeValue(2))

chart = (line + rule)
Exemple #14
0
        terminal_vowel_prop = len(terminal_vowels) / word_size

        init_vowels = filter_dict(word_data, 'init_vowel', 1)
        init_vowels_prop = len(init_vowels) / word_size
        cognates = filter_dict(word_data, 'cognate', 1)

        ls_types = [
            'initial letter', 'terminal letter', 'cognate status',
            'initial letter', 'terminal letter', 'cognate status'
        ]

        alt.Chart(word_data).mark_text(filled=True).encode(
            alt.X('term_vowel:O', axis=None),
            alt.Y('animal:O', axis=None),
            alt.Row('country:N', header=alt.Header(title='')),
            alt.SizeValue(60),
            text='emoji').properties(width=800, height=200)

        # https://vega.github.io/vega-lite/examples/isotype_bar_chart_emoji.html

    elif descriptive_stats_choice == descriptive_stats_options[3]:
        # write information on total dataset
        total_accuracy = ipa.get_proportions(study_data)
        total_accuracy_mean = np.mean(total_accuracy)
        total_accuracy_std = np.std(total_accuracy)
        st.write("### All participants")
        st.write(
            "Across all of the sample, the particpants scored an average of " +
            str(round((total_accuracy_mean * 100), 2)) +
            "% vowel pronunciation accuracy with a standard deviation of: " +
            str(round((total_accuracy_std * 100), 2)) + "%")
Exemple #15
0
"""
Histogram with a Global Mean Overlay
------------------------------------
This example shows a histogram with a global mean overlay.
"""

import altair as alt
from vega_datasets import data

source = data.movies.url

bar = alt.Chart(source).mark_bar().encode(x=alt.X('IMDB_Rating:Q',
                                                  bin=True,
                                                  axis=None),
                                          y=alt.Y('count(*):Q'))

rule = alt.Chart(source).mark_rule(color='red').encode(x='mean(IMDB_Rating):Q',
                                                       size=alt.SizeValue(5))
chart = bar + rule
Exemple #16
0
    'col': 2
}, {
    'country': 'United States',
    'animal': 'sheep',
    'col': 1
}])

domains = ['person', 'cattle', 'pigs', 'sheep']

shape_scale = alt.Scale(
    domain=domains,
    range=[
        'M1.7 -1.7h-0.8c0.3 -0.2 0.6 -0.5 0.6 -0.9c0 -0.6 -0.4 -1 -1 -1c-0.6 0 -1 0.4 -1 1c0 0.4 0.2 0.7 0.6 0.9h-0.8c-0.4 0 -0.7 0.3 -0.7 0.6v1.9c0 0.3 0.3 0.6 0.6 0.6h0.2c0 0 0 0.1 0 0.1v1.9c0 0.3 0.2 0.6 0.3 0.6h1.3c0.2 0 0.3 -0.3 0.3 -0.6v-1.8c0 0 0 -0.1 0 -0.1h0.2c0.3 0 0.6 -0.3 0.6 -0.6v-2c0.2 -0.3 -0.1 -0.6 -0.4 -0.6z',
        'M4 -2c0 0 0.9 -0.7 1.1 -0.8c0.1 -0.1 -0.1 0.5 -0.3 0.7c-0.2 0.2 1.1 1.1 1.1 1.2c0 0.2 -0.2 0.8 -0.4 0.7c-0.1 0 -0.8 -0.3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-0.3 0.6c-0.1 0.2 0 0.3 -0.1 0.5c-0.1 0.2 -0.1 0.2 -0.2 0.3c-0.1 0.1 0.3 1.1 0.3 1.1l-0.3 0c0 0 -0.3 -0.9 -0.3 -1c0 -0.1 -0.1 -0.2 -0.3 -0.2c-0.2 0 -0.3 0.1 -0.4 0.4c0 0.3 -0.2 0.8 -0.2 0.8l-0.3 0l0.3 -1c0 0 0.1 -0.6 -0.2 -0.5c-0.3 0.1 -0.2 -0.1 -0.4 -0.1c-0.2 -0.1 -0.3 0.1 -0.4 0c-0.2 -0.1 -0.3 0.1 -0.5 0c-0.2 -0.1 -0.1 0 -0.3 0.3c-0.2 0.3 -0.4 0.3 -0.4 0.3l0.2 1.1l-0.3 0l-0.2 -1.1c0 0 -0.4 -0.6 -0.5 -0.4c-0.1 0.3 -0.1 0.4 -0.3 0.4c-0.1 -0.1 -0.2 1.1 -0.2 1.1l-0.3 0l0.2 -1.1c0 0 -0.3 -0.1 -0.3 -0.5c0 -0.3 0.1 -0.5 0.1 -0.7c0.1 -0.2 -0.1 -1 -0.2 -1.1c-0.1 -0.2 -0.2 -0.8 -0.2 -0.8c0 0 -0.1 -0.5 0.4 -0.8z'
    ])

color_scale = alt.Scale(domain=domains,
                        range=[
                            'rgb(162,160,152)', 'rgb(194,81,64)',
                            'rgb(93,93,93)', 'rgb(91,131,149)'
                        ])

alt.Chart(df).mark_point(filled=True).encode(
    alt.X('col:O', axis=None), alt.Y('animal:O', axis=None),
    alt.Row('country:N', header=alt.Header(title='')),
    alt.Shape('animal:N', legend=None, scale=shape_scale),
    alt.Color('animal:N', legend=None, scale=color_scale), alt.OpacityValue(1),
    alt.SizeValue(200)).properties(width=800, height=200)
Exemple #17
0
brush = alt.selection(type='interval', encodings=['x'])

bars = alt.Chart().mark_bar().encode(
    x='Years:Q',
    y='Unemployement Rate:Q',
    opacity=alt.condition(brush, alt.OpacityValue(1), alt.OpacityValue(0.7)),
).properties(
    width=400,
    height=300).add_selection(
    brush
)

line = alt.Chart().mark_rule(color='firebrick').encode(
    y='mean(Unemployement Rate):Q',
    size=alt.SizeValue(3)
).transform_filter(
    brush
)

df1 = df_hist1_sorted.loc[0,:][Unemployment_rate_columns].values
df1 = pd.DataFrame(df1 , date_range)
df1 = df1.reset_index()
df1.columns = ['Years','Unemployement Rate']


df2 = df_hist1_sorted.loc[1,:][Unemployment_rate_columns].values
df2 = pd.DataFrame(df2 , date_range)
df2 = df2.reset_index()
df2.columns = ['Years','Unemployement Rate']
Exemple #18
0
"""
Interactive Average
===================
The plot below uses an interval selection, which causes the chart to include an interactive brush
(shown in grey). The brush selection parameterizes the red guideline, which visualizes the average
value within the selected interval.
"""
# category: interactive charts
import altair as alt
from vega_datasets import data

weather = data.seattle_weather.url
brush = alt.selection(type='interval', encodings=['x'])

bars = alt.Chart().mark_bar().encode(
    alt.X('date:O', timeUnit='month'),
    y='mean(precipitation):Q',
    opacity=alt.condition(brush, alt.OpacityValue(1),
                          alt.OpacityValue(0.7))).properties(selection=brush)

line = alt.Chart().mark_rule(color='firebrick').encode(
    y='mean(precipitation):Q',
    size=alt.SizeValue(3)).transform_filter(brush.ref())

alt.layer(bars, line, data=weather)
Exemple #19
0
"""
Interactive Average
===================
The plot below uses an interval selection, which causes the chart to include an interactive brush
(shown in grey). The brush selection parameterizes the red guideline, which visualizes the average
value within the selected interval.
"""
# category: interactive charts
import altair as alt
from vega_datasets import data

weather = data.seattle_weather.url
brush = alt.selection(type='interval', encodings=['x'])

bars = alt.Chart().mark_bar().encode(
    x='month(date):O',
    y='mean(precipitation):Q',
    opacity=alt.condition(brush, alt.OpacityValue(1),
                          alt.OpacityValue(0.7))).add_selection(brush)

line = alt.Chart().mark_rule(color='firebrick').encode(
    y='mean(precipitation):Q', size=alt.SizeValue(3)).transform_filter(brush)

alt.layer(bars, line, data=weather)
#color changing marks
rating_radio = alt.binding_radio(options=ratings)

rating_select = alt.selection_single(fields=['MPAA_Rating'], bind=rating_radio, name="Rating")
rating_color_condition = alt.condition(rating_select,
                      alt.Color('MPAA_Rating:N', legend=None),
                      alt.value('lightgray'))

highlight_ratings = base.add_selection(
    rating_select
).encode(
    color=rating_color_condition
).properties(title="Radio Button Highlighting")

# Boolean selection for format changes
input_checkbox = alt.binding_checkbox()
checkbox_selection = alt.selection_single(bind=input_checkbox, name="Big Budget Films")

size_checkbox_condition = alt.condition(checkbox_selection,
                                        alt.SizeValue(25),
                                        alt.Size('Hundred_Million_Production:Q')
                                       )

budget_sizing = base.add_selection(
    checkbox_selection
).encode(
    size=size_checkbox_condition
).properties(title="Checkbox Formatting")

( filter_year | filter_genres) &  (highlight_ratings | budget_sizing  )