Altair

Altair

Here’s a advanced and useful sample code using Altair, which demonstrates how to create a layered chart with interactivity, such as tooltips and selection, along with custom encoding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import altair as alt
from vega_datasets import data

# Load dataset
source = data.cars()

# Define a brush selection
brush = alt.selection(type='interval')

# Base chart with a scatter plot
base = alt.Chart(source).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color=alt.condition(brush, 'Origin:N', alt.value('lightgray')),
tooltip=['Name:N', 'Origin:N', 'Horsepower:Q', 'Miles_per_Gallon:Q']
).properties(
width=600,
height=400
).add_selection(
brush
)

# Layer a bar chart on top that shows the distribution of 'Origin' for selected points
bars = alt.Chart(source).mark_bar().encode(
x='count():Q',
y='Origin:N',
color='Origin:N'
).transform_filter(
brush
)

# Combine the scatter plot and the bar chart
chart = base & bars
chart

Result

Explanation

  • Brush Selection:
    An interactive selection that allows users to drag over the scatter plot to select a region.
  • Scatter Plot:
    A basic plot where points are colored by their origin, and the color changes based on the selection.
  • Bar Chart:
    Shows the distribution of car origins, updated based on the selection made in the scatter plot.
  • Interactivity:

Tooltips provide detailed information when hovering over the points, and the chart updates dynamically based on the user’s selection.

This example combines interactivity with advanced encoding and layout, making it useful for exploratory data analysis.