How to Create Interactive Scatter Plots with Altair

How to Create Interactive Scatter Plots with Altair

Altair is a Python library that transforms your data into interactive visualizations using a simple, declarative API. Under the hood, Altair converts your Python code into Vega-Lite specifications, which are then rendered by the Vega visualization framework. This combination allows you to create sophisticated visualizations with minimal code while leveraging Vega’s robust rendering engine and Vega-Lite’s concise grammar. Think of Altair as the Python interface that makes these powerful visualization tools accessible to data scientists and analysts.

Setting Up Your Environment

Before creating visualizations with Altair, you’ll need to set up your Python environment. The most reliable way to do this is using conda:

1. First, create a new conda environment:

 
conda create -n altair_env python=3.9
conda activate altair_env

2. Install Altair with all its dependencies:

 
conda install -c conda-forge altair-all

3. If you are using a Jupyter Notebook, you can install a separate kernel that links directly to this new environment by executing the below: 

 
conda install ipykernel
python -m ipykernel install --user --name altair_env --display-name "Python (Altair)"

4. Install the dataset package:

 
conda install -c conda-forge vega_datasets

Once installed, launch Jupyter Notebook and select the “Python (Altair)” kernel. For more detailed information regarding the setup, here is the link to the official documentation. 

Starting with the Basics

Let’s begin with a simple scatter plot using data from the vega_datasets package, which provides convenient access to commonly used datasets for visualization examples. We’ll be working with the Gapminder dataset, a comprehensive collection of global development indicators that tracks how countries have evolved over time. For our initial visualization, we’ll focus on two key metrics from the year 2000: fertility rate (average number of children per woman) and life expectancy (average lifespan in years). As we progress, we’ll enhance our visualization by incorporating additional variables like regional clusters and population size to reveal more complex patterns in global development.

 
# Basic scatter plot - Just points showing the relationship
import altair as alt
from vega_datasets import data

# Load data
gapminder = data.gapminder().query('year == 2000')

# Create basic scatter plot
basic_plot = alt.Chart(gapminder).mark_circle().encode(
    x='fertility:Q',  # Q for quantitative
    y='life_expect:Q',
    tooltip=['country:N', 'fertility:Q', 'life_expect:Q']  # N for nominal
).properties(
    title='Fertility Rate vs Life Expectancy (2000)',
    width=400,
    height=300
)

basic_plot

In this first example, we’re creating a basic scatter plot where:

  • Each point represents a country
  • The x-axis shows the fertility rate
  • The y-axis shows life expectancy
  • We’ve added basic tooltips that appear when hovering over points
  • The :Q suffix tells Altair this is quantitative (numeric) data
  • The :N suffix indicates nominal (categorical) data

The resulting plot shows a clear negative correlation: countries with higher fertility rates tend to have lower life expectancy.

Basic scatter plot showing the relationship between fertility rate and life expectancy in 2000, with all points in blue and no size variation
Basic scatter plot showing the relationship between fertility rate and life expectancy in 2000, with all points in blue and no size variation | Image by Author

Adding Color Encoding

Next, let’s enhance our visualization by adding color to represent different regions or clusters:

 
# Medium level - Add color and tooltips
medium_plot = alt.Chart(gapminder).mark_circle().encode(
    x='fertility:Q',
    y='life_expect:Q',
    color='cluster:N',
    tooltip=['country:N', 'cluster:N', 'fertility:Q', 'life_expect:Q']
).properties(
    title='Fertility Rate vs Life Expectancy by Region (2000)',
    width=400,
    height=300
)

medium_plot

This version adds:

  • Color encoding based on clusters/regions
  • Enhanced tooltips that now include the cluster information
  • The same basic structure but with more visual information

The colored version reveals patterns we couldn’t see before: certain regions tend to cluster together, suggesting geographical and developmental relationships.

imple scatter plot of fertility rate versus life expectancy by region in 2000, showing points color-coded by cluster, with no population sizing
imple scatter plot of fertility rate versus life expectancy by region in 2000, showing points color-coded by cluster, with no population sizing | Image by Author

Creating a Fully Interactive Visualization

Finally, let’s create a more sophisticated interactive visualization that includes population data:

 
# Interactive version - Add zooming and size encoding
interactive_plot = alt.Chart(gapminder).mark_circle().encode(
    x='fertility:Q',
    y='life_expect:Q',
    color='cluster:N',
    size='pop:Q',  # Q for quantitative
    tooltip=['country:N', 'cluster:N', 
             'fertility:Q', 'life_expect:Q', 
             'pop:Q']
).properties(
    title='Interactive Global Development Indicators (2000)',
    width=400,
    height=300
).interactive()

interactive_plot

This final version includes several advanced features:

  • Circle sizes that represent population (pop:Q)
  • Interactive zooming and panning capabilities (.interactive())
  • Comprehensive tooltips showing all relevant data
  • The same color coding as before

The interactive() method adds powerful features:

  • Click and drag to zoom into specific areas
  • Double-click to reset the view
  • Hover over points to see detailed information

This visualization now tells a much richer story, showing not just the relationship between fertility and life expectancy, but also how population size and regional differences play into global development patterns.

Scatter plot of fertility rate versus life expectancy in 2000, with points sized by population and color-coded by cluster, showing two prominent large circles
Scatter plot of fertility rate versus life expectancy in 2000, with points sized by population and color-coded by cluster, showing two prominent large circles | Image by Author

Interactive Features in Action

Let’s explore how the interactive features enhance our ability to analyze the data. When we zoom into different regions of the plot, we can uncover interesting details that might be missed in the overview. For example, we can see China (cluster 4) has achieved a relatively high life expectancy of 72 years while maintaining a low fertility rate of 1.7, with a population of over 1.2 billion represented by the large green circle. 

Scatter plot showing global development indicators for 2000, highlighting China with fertility rate 1.7 and life expectancy 72 years. Points are color-coded by cluster and sized by population.
Scatter plot showing global development indicators for 2000, highlighting China with fertility rate 1.7 and life expectancy 72 years. Points are color-coded by cluster and sized by population | Image by Author

By zooming out to see the full picture again, we can spot countries like Nigeria (cluster 2) at the other end of the spectrum, with a much higher fertility rate of 5.8 and lower life expectancy of 46.6 years.

Scatter plot showing global development indicators for 2000, highlighting Nigeria with fertility rate 5.8 and life expectancy 46.6 years. Points are color-coded by cluster and sized by population
Scatter plot showing global development indicators for 2000, highlighting Nigeria with fertility rate 5.8 and life expectancy 46.6 years. Points are color-coded by cluster and sized by population | Image by Author

This ability to zoom in and out, combined with the hover tooltips showing precise values, makes it possible to conduct both broad pattern analysis and detailed country-specific investigations within the same visualization. The interactive nature of the plot turns what could have been a static display of data into an exploratory tool for understanding global development patterns.

By building up from simple to complex, we can see how Altair makes it straightforward to create sophisticated interactive visualizations with just a few lines of code. Each addition to the plot adds another layer of information while maintaining clarity and usability.

Leave a Reply

Your email address will not be published. Required fields are marked *