Interactive Data Viz using Altair
By: Samarth Gupta
Tags: Data Visualization, Python, Dashboard, Interactive, Altair

While working on a Data Viz project, everyone wants to present interactive plots on their notebooks and dashboards. Although it seems quite a daunting task to build effective & interactive plots. Recently I came across a gem of an Open Source Data Visualization library, called Altair.

About:

Altair is an open-source python library used for declarative statistical visualization and is based on Vega and Vega-Lite. Altair provides an effective and concise visualization grammar that allows us to construct an extensive variety of statistical visualizations quickly.

Thus we can give more time to exploring our data by building elegant and effective plots rather than just struggling with code.

Installation:

Altair can be installed, along with the example datasets in vega_datasets, using:

$ pip install altair

or

$ pip install altair vega_datasets

For Conda package manager, the equivalent is:

$ conda install -c conda-forge altair vega_datasets

Let's build an interactive chart for the below Case Study :

This article covers a small case study and provides step by step procedure to build interactive charts. If you want the final code directly jump to the bottom or check this Repo.

We will take the Seattle weather dataset which contains daily weather-observations from Seattle for the years 2012–2015.

Interactive Concatenated Scatter Plot & Bar Chart

This chart provides an interactive exploration of Seattle weather over the year. It includes a one-axis brush selection & Clicks selection to easily see the distribution of weather types in a particular date range.

1. Importing the dataset:

Since we installed Altair with example datasets, we can import the datasets or we can use Pandas to import data from CSV.

import altair as alt

from vega_datasets import data

settle_data = data.seattle_weather()

settle_data.head() or import altair as alt

import pandas as pd

settle_data = pd.read_csv("/content/seattle-weather.csv")

settle_data.head()

The data used internally by Altair is stored in a Pandas DataFrame format, but it supports multiple input formats. This is the best part, we can manipulate our data in Altair just like how you deal with Pandas DataFrame.

2. Defining the scale:

settle_data.weather.unique()

>> array(['drizzle', 'rain', 'sun', 'snow', 'fog'], dtype=object)

We will be plotting data based on the Distribution of Weather types. As we look at the ‘weather’ column, we find 5 categories, which are defined on the scale.

# Defining the color scale for the plot (distribution based on Weather types) scale = alt.Scale(domain=['sun', 'fog', 'drizzle', 'rain', 'snow'],range=['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd']) color = alt.Color('weather:N', scale=scale)

# N : used to specify nominal data

3. Top Scatter plot: Temperature Vs Date

x-axis: date, y-axis: temperature

We are interested in knowing the correlation between temperature with Date(Time). We specify the kind of plot we want to make by using make_point() fn to show data as points.

fn to show data as points. We pass the data to alt.Chart() function.

points = alt.Chart(settle_data).mark_point().encode(

alt.X('monthdate(date):T', title='Date'),

alt.Y('temp_max:Q',

title='Maximum Daily Temperature (C)',

scale=alt.Scale(domain=[-5, 40])

) # T- Specify Time data

# Q- Specify quantitative data

# O- Specify ordinal data

Scatter Plot

We can make our plot more Informative by adding one more attribute i.e. precipitation measure(take a look at the dataset), as size property.

points = alt.Chart().mark_point().encode(

alt.X('monthdate(date):T', title='Date'),

alt.Y('temp_max:Q',title='Maximum Daily Temperature (C)',

scale=alt.Scale(domain=[-5, 40]),

size=alt.Size('precipitation:Q',scale=alt.Scale(range=[5, 200])

)

)

Precipitation attribute added

Make sure every time an attribute is added, it should be enclosed inside the encode() function and separated by commas.

In altair, the mapping of visual properties to data columns is referred to as an encoding. Thus we need to define the encoding for each chart, in order to define the properties.

4. Add Interactive Features:

We will use selection() function, which can be used for creating interactive images.

We will add a brush that is active on the top panel which can be used for an interval selection using the selection_interval() function, to select the Time Interval (encoding: x-axis i.e. Date/Time

brush = alt.selection_interval(encodings=['x'])

Next, we will add the brush to our chart. We will also use condition() fn to provide conditional color encoding(for different weather types) to the plot, based on interval selection.

points = alt.Chart(settle_data).mark_point().encode(

alt.X('monthdate(date):T', title='Date'),

alt.Y('temp_max:Q',

title='Maximum Daily Temperature (C)',

scale=alt.Scale(domain=[-5, 40])

),

color=alt.condition(brush, color, alt.value('lightgray')),

size=alt.Size('precipitation:Q', scale=alt.Scale(range=[5, 200]))).add_selection(

brush

)

points

Brush to select an interval from the x-axis (date)

5. Bottom bar Plot: Weather type

x-axis: Weather, y-axis: Count of Records

We use make_bar() fn to show data as a barplot.

bars = alt.Chart(settle_data).mark_bar().encode(

x='count()',

y='weather:N')

barplot (weather Vs Records)

Next, we add an interactive feature, a multi-click that is a selection tool based on weather type, shown by color.

click = alt.selection_multi(encodings=['color'])

We bind it to the chart, along with adding a condition() fn.

bars = alt.Chart(settle_data).mark_bar().encode(

x='count()',

y='weather:N',

color=alt.condition(click, color, alt.value('lightgray')),

).add_selection(

click

)

6. Building Compound Chart: Concat both the charts Vertically:

Here comes the final part of our case study, we will be Vertically Concatting both the plots, as you saw at the beginning.

We will use vconcat(plot1, plot2, data,) function, to stack the plots, and also made some tweaks to our prior codes, so that both plots are connected and, behave as a single interactive chart. You can also refer to other types of Compound charts.

alt.vconcat(

points,

bars,

data=settle_data,

title="Seattle Weather: 2012-2015"

)

7. Final Code:

Some Important tweaks made:

When we use a Compound plot, the dataset (here: seattle_data), is passed as an input to the vconcat(), and not to the individual plot functions i.e. alt.Chart().

Also, properties() is used to provide equal width & height, to each chart.

Filter Transform (brush)

Filter Transform ( Click )