import altair as altimport numpy as npimport pandas as pd# Compute x^2 + y^2 across a 2D gridx, y = np.meshgrid(range(-5, 5), range(-5, 5))z = x **2+ y **2# Convert this grid to columnar data expected by Altairsource = pd.DataFrame({'x': x.ravel(),'y': y.ravel(),'z': z.ravel()})alt.Chart(source).mark_rect().encode( x='x:O', y='y:O', color='z:Q')
import altair as altimport pandas as pdimport numpy as npnp.random.seed(0)n_objects =20n_times =50# Create one (x, y) pair of metadata per objectlocations = pd.DataFrame({'id': range(n_objects),'x': np.random.randn(n_objects),'y': np.random.randn(n_objects)})# Create a 50-element time-series for each objecttimeseries = pd.DataFrame(np.random.randn(n_times, n_objects).cumsum(0), columns=locations['id'], index=pd.RangeIndex(0, n_times, name='time'))# Melt the wide-form timeseries into a long-form viewtimeseries = timeseries.reset_index().melt('time')# Merge the (x, y) metadata into the long-form viewtimeseries['id'] = timeseries['id'].astype(int) # make merge not complaindata = pd.merge(timeseries, locations, on='id')# Data is prepared, now make a chartselector = alt.selection_point(fields=['id'])base = alt.Chart(data).properties( width=250, height=250).add_params(selector)points = base.mark_point(filled=True, size=200).encode( x='mean(x)', y='mean(y)', color=alt.condition(selector, 'id:O', alt.value('lightgray'), legend=None),)timeseries = base.mark_line().encode( x='time', y=alt.Y('value').scale(domain=(-15, 15)), color=alt.Color('id:O').legend(None)).transform_filter( selector)points | timeseries
import altair as altfrom vega_datasets import datasource = data.seattle_weather()color = alt.Color('weather:N').scale( domain=['sun', 'fog', 'drizzle', 'rain', 'snow'],range=['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd'])# We create two selections:# - a brush that is active on the top panel# - a multi-click that is active on the bottom panelbrush = alt.selection_interval(encodings=['x'])click = alt.selection_point(encodings=['color'])# Top panel is scatter plot of temperature vs timepoints = alt.Chart().mark_point().encode( alt.X('monthdate(date):T').title('Date'), alt.Y('temp_max:Q') .title('Maximum Daily Temperature (C)') .scale(domain=[-5, 40]), alt.Size('precipitation:Q').scale(range=[5, 200]), color=alt.condition(brush, color, alt.value('lightgray')),).properties( width=550, height=300).add_params( brush).transform_filter( click)# Bottom panel is a bar chart of weather typebars = alt.Chart().mark_bar().encode( x='count()', y='weather:N', color=alt.condition(click, color, alt.value('lightgray')),).transform_filter( brush).properties( width=550,).add_params( click)alt.vconcat( points, bars, data=source, title="Seattle Weather: 2012-2015")