
Altair is a statistical visualization library for Python that allows you to create complex, interactive charts using a simple and intuitive API. In this article, we will be working with Seattle’s weather data from 2012-2015, which includes daily records of precipitation, temperature, and weather conditions. This dataset is perfect for demonstrating various bar chart techniques as it contains both numerical and categorical data with temporal components. It is also readily available within the vega_datasets package which synchronizes well with Altair given that it is built on top of Vega and Vega-Lite. For a detailed guide on how to set up this package and your environment, please kindly refer to this post or the official documentation.
Basic Monthly Precipitation Bar Chart
Let’s start with a straightforward bar chart showing average monthly precipitation:
import altair as alt
from vega_datasets import data
# Load the Seattle weather dataset
weather = data.seattle_weather()
# Create a basic monthly precipitation bar chart
basic_chart = alt.Chart(weather).mark_bar().encode(
x=alt.X('month(date):O', title='Month'),
y=alt.Y('mean(precipitation):Q',
title='Average Precipitation (mm)',
axis=alt.Axis(grid=True)),
tooltip=[
alt.Tooltip('month(date):O', title='Month'),
alt.Tooltip('mean(precipitation):Q', title='Avg Precipitation (mm)', format='.1f')
]
).properties(
width=600,
height=300,
title='Average Monthly Precipitation in Seattle (2012-2015)'
)
basic_chart
This code introduces several key Altair concepts:
- mark_bar(): Specifies we want to create a bar chart
- encode(): Maps data variables to visual properties
- month(date):O: Extracts month from date column and treats it as Ordinal data
- mean(precipitation):Q: Automatically calculates the mean of precipitation values
- tooltip: Adds interactive hover information
The resulting visualization clearly shows Seattle’s seasonal precipitation pattern, with notably wetter winters and drier summers.

Bar graph showing average monthly precipitation in Seattle from 2012-2015, measured in millimeters. Shows highest rainfall in November and March, lowest in July | Image by Author
Grouped Bar Chart for Temperature Comparison
Next, we’ll create a more complex grouped bar chart to compare maximum and minimum temperatures:
# Create a grouped bar chart for temperature data
grouped_temp = alt.Chart(weather).transform_fold(
['temp_max', 'temp_min'],
as_=['Measurement', 'Temperature']
).mark_bar().encode(
x=alt.X('month(date):O', title='Month',
axis=alt.Axis(labelAngle=0)), # Make month labels horizontal
xOffset='Measurement:N', # This creates the grouped effect
y=alt.Y('mean(Temperature):Q',
title='Temperature (°C)',
scale=alt.Scale(domain=[0, 28])), # Set y-axis range
color=alt.Color('Measurement:N',
scale=alt.Scale(
domain=['temp_max', 'temp_min'],
range=['#ff9900', '#3377cc']
),
title='Temperature'),
tooltip=[
alt.Tooltip('month(date):O', title='Month'),
alt.Tooltip('Measurement:N', title='Type'),
alt.Tooltip('mean(Temperature):Q', title='Temperature (°C)', format='.1f')
]
).properties(
width=600,
height=300,
title='Average Monthly Maximum and Minimum Temperatures (°C)'
)
grouped_temp
This visualization introduces advanced techniques:
- transform_fold(): Reshapes the data to combine max/min temperatures
- xOffset: Creates grouped bars by shifting based on measurement type
- scale=alt.Scale(domain=[0, 28]): Sets fixed y-axis range
- Custom color scheme using scale=alt.Scale(domain=…, range=…)
The output effectively shows the temperature range across months, with orange bars for maximum and blue bars for minimum temperatures.

Bar graph displaying average monthly maximum (orange) and minimum (blue) temperatures in Celsius throughout the year. Shows peak temperatures in summer months and lowest in winter | Image by Author
Interactive Stacked Bar Chart for Weather Types
Finally, we’ll create an interactive stacked bar chart showing weather patterns:
# Create an interactive stacked bar chart
selection = alt.selection_point(
fields=['weather'],
bind='legend',
name='Weather Type'
)
stacked_chart = alt.Chart(weather).mark_bar().encode(
x=alt.X('month(date):O', title='Month'),
y=alt.Y('count():Q', title='Number of Days',
stack='normalize'),
color=alt.Color('weather:N',
scale=alt.Scale(scheme='category20')),
opacity=alt.condition(selection, alt.value(1), alt.value(0.2)),
tooltip=['month(date):O', 'weather:N', 'count():Q']
).add_params(
selection
).properties(
width=600,
height=400,
title='Proportion of Weather Types by Month'
).configure_legend(
orient='bottom',
titleFontSize=12,
labelFontSize=11
)
stacked_chart
This chart showcases Altair’s interactive capabilities:
- selection_point(): Creates interactive legend selection
- stack=’normalize’: Converts to percentage stack
- opacity=alt.condition(): Highlights selected weather types
- configure_legend(): Customizes legend appearance
The visualization’s interactive nature is particularly powerful. When all weather types are displayed (first image), we can see the complete distribution of weather patterns throughout the year. This reveals that Seattle experiences a mix of weather conditions, with more sunny days during summer months and increased precipitation (rain, drizzle) during winter.

https://www.statology.org/wp-content/uploads/2024/11/Screenshot-2024-11-19-at-12.52.22.png” alt=”Stacked bar chart showing the proportion of different weather types (sun, rain, fog, drizzle, and snow) for each month of the year. Summer months show more sun while winter months have more rain and fog | Image by Author
However, the true strength of this visualization lies in its interactive legend. By selecting specific weather types, we can focus on particular patterns. For example, when we select only ‘rain’ (image below), the chart clearly highlights the annual rainfall pattern. The opacity of non-selected weather types is automatically reduced to 0.2 (20%), making it easy to focus on our selection while maintaining context.

Stacked 100% bar chart showing daily weather patterns in Seattle across months. Each bar represents a month and is divided into five weather types: sun (green), rain (orange), fog (light gray), drizzle (blue), and snow (beige). The chart opts to highlight the rainy days while dimming the other weather types through its interactive function | Image by Author
This interaction reveals that:
- Rain is most prevalent during winter months (November through February)
- Summer months (June through August) see significantly less rainfall
- There’s a gradual transition in rainfall patterns during spring and fall
This interactive functionality, implemented through Altair’s selection_point() and alt.condition(), transforms what could have been a static stacked bar chart into a dynamic tool for weather pattern analysis. Users can toggle between different weather types or combinations thereof, making it easier to identify specific seasonal patterns while maintaining the context of the overall weather distribution.
Each of these visualizations builds upon the previous one, demonstrating how Altair’s declarative syntax can create increasingly sophisticated charts while maintaining readable and maintainable code. The interactive features and careful attention to visual design make these charts both informative and engaging for data analysis.
