How to Create Interactive Plots with Altair | by Khuyen Tran | Towards Data Science

Have you ever wanted to take a closer look at your data by zooming in, highlight points of interest, or see how the data change over time with a slider bar? By having more control over your static graph, you figure you might get much more insights into the data.
But you imagine it must be challenging to create an interactive plot. So you decide not to bother with the interactive part. What if there is a python library that enables you to do exactly that with several lines of Python codes?
The graph above is created with Altair. Altair is a statistical visualization library for Python, based on Vega and Vega-Lite. Altair offers a powerful and concise visualization grammar for quickly building a wide range of statistical graphics. You just need to declare links between data fields, color, size, etc, while letting the rest of the plot details handled automatically. With Altair, you can spend more time understanding your data and its meaning than figuring out the codes.
Install Altair
$ pip install altair
Altair can be installed along with the example datasets in vega_datasets:
$ pip install altair vega_datasets
Import Altair on your Jupyter Notebook
import altair as altimport pandas as pd
Some datasets in Altair are built around Pandas DataFrame. What does this mean? It means that you can manipulate data in Altair just like how you deal with Pandas DataFrame.
We will use gapminder data in vega_data to visualize global health and population data for some countries over the time period of 1995 to 2005.
from vega_datasets import data as vega_datagap = pd.read_json(vega_data.gapminder.url)gap.head(10)
Find out how many unique years are in this data:
>>> gap.year.unique()array([1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005])
Since we are mostly interested in the latest data, let’s take a look at data in 2005.
gap2005 = gap.loc[gap['year'] == 2005]
We are curious about the correlation between fertility and life expectancy. So we specify the kind of plot we want to make with mark_point() to show data as points. We can also present the data with other geometric shapes using mark_*
alt.Chart(gap2005).mark_point().encode(    alt.X('fertility'),    alt.Y('life_expect'))
Look like the data is not in the center of the graph. Normally we would need to specify the scale with matplotlib but with Altair, you just need to use scale method
Nice! But what if we want to see how the population size is related to fertility and life expectancy? We could utilize another dimension: Size
Awesome. The legend on the left-hand side gives us the meaning of each circle’s size. Can we add another dimension? Absolutely! x-axis, y-axis, size, what are we missing? Color!
As you can see above, we could also specify the type of data: N-Nominal (categories name), Q-Quantitative (numerical data), O-Ordinal (ordered data), or T-Temporal (time points or intervals). In the code above, since I want to cluster to be interpreted as categories data, I use :N
To make our circles look nicer, we fill the point with color using filled=True. Add some opacity to see the smaller points behind the big points using alt.OpacityValue(0.5)
But there are many points in the graph. Is there a way that when we click on each point to show the information about the country, fertility and life expectancy? Yes of course. That can be done with adding Tooltip
Being able to see the information on each point is nice. But what if we want to see the information about multiple points at once? Without further waiting, let’s jump on how to create an interactive plot with Altair!
Selection_single() enables us to click one point to highlight it. As we click on the point, we want other points to become non-relevant with gray color. This could be done with alt.condition()
Now we can look at the information of the point of interest without being distracted by other points
But we might be interested in several points at once. Or better, to select an interval of points. Both could be done with selection_multi() and selection_interval()
Since we want to try out with different selection tools at once, let’s create a function to do it.
Now use alt.hconcat() to try out with different selections and concatenate the graphs of those selections
We have been seeing the data for the year 2005. What if we want to see the change of data over time? That could be easily done by adding some more conditions for alt.selection_single such as name=’select’, fields = [‘year’], the initial year init={‘year’: 1955} and range bind=alt.binding_range(min=1955, max=2005, step=5)
Nice! Now we can easily see the change of the data over time by dragging the mouse on the select-year bar
What is the last function that we want from our graph after creating it? Save our graph to show our websites or social media! And this can be easily done by clicking on the button in the left corner of the graph.
Congratulations! You have learned how to utilize Altair for efficient data analysis. This article does not exhaustively cover everything you can do with Altair such as creating a stacked bar chart, heatmap, area chart, map or other interactive functions. You can find out more about Altair Libary here or follow the Github tutorial. What I hope you to get out the most of this article is that: creating an interesting and beautiful graph with Python can be incredibly easy and fun!
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Heer, Jeffrey. Github: https://github.com/uwdata/visualization-curriculum. Jan 2017.