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 altfrom vega_datasets import dataimport geopandas as gpd# load datagdf_quakies = gpd.read_file(data.earthquakes.url, driver="GeoJSON")gdf_world = gpd.read_file(data.world_110m.url, driver="TopoJSON")# defintion for interactive brushbrush = alt.selection_interval( encodings=["longitude"], empty=False, value={"longitude": [-50, -110]})# world disksphere = alt.Chart(alt.sphere()).mark_geoshape( fill="transparent", stroke="lightgray", strokeWidth=1)# countries as shapesworld = alt.Chart(gdf_world).mark_geoshape( fill="lightgray", stroke="white", strokeWidth=0.1)# earthquakes as dots on mapquakes = alt.Chart(gdf_quakies).transform_calculate( lon="datum.geometry.coordinates[0]", lat="datum.geometry.coordinates[1]",).mark_circle(opacity=0.35, tooltip=True).encode( longitude="lon:Q", latitude="lat:Q", color=alt.condition(brush, alt.value("goldenrod"), alt.value("steelblue")), size=alt.Size("mag:Q").scale(type="pow", range=[1, 1000], domain=[0, 7], exponent=4),).add_params(brush)# combine layers for the mapleft_map = alt.layer(sphere, world, quakes).project(type="mercator")# histogram of binned earthquakesbars = alt.Chart(gdf_quakies).mark_bar().encode( x=alt.X("mag:Q").bin(extent=[0,7]), y="count(mag):Q", color=alt.value("steelblue"))# filtered earthquakesbars_overlay = bars.encode(color=alt.value("goldenrod")).transform_filter(brush)# combine layers for histogramright_bars = alt.layer(bars, bars_overlay)# vertical concatenate map and barsleft_map | right_bars
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.disasters.urlalt.Chart(source).transform_filter( alt.datum.Entity !='All natural disasters').mark_circle( opacity=0.8, stroke='black', strokeWidth=1, strokeOpacity=0.4).encode( alt.X('Year:T') .title(None) .scale(domain=['1899','2018']), alt.Y('Entity:N') .title(None) .sort(field="Deaths", op="sum", order='descending'), alt.Size('Deaths:Q') .scale(range=[0, 2500]) .title('Deaths') .legend(clipHeight=30, format='s'), alt.Color('Entity:N').legend(None), tooltip=["Entity:N", alt.Tooltip("Year:T", format='%Y'), alt.Tooltip("Deaths:Q", format='~s') ],).properties( width=450, height=320, title=alt.Title( text="Global Deaths from Natural Disasters (1900-2017)", subtitle="The size of the bubble represents the total death count per year, by type of disaster", anchor='start' )).configure_axisY( domain=False, ticks=False, offset=10).configure_axisX( grid=False,).configure_view( stroke=None)
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")