Grapher
owid.grapher.Chart ¶
Create interactive OWID charts from pandas DataFrames.
The Chart class provides a declarative API for building interactive visualizations using OWID's Grapher library. Charts are configured through method chaining and render directly in Jupyter notebooks.
Multiple chart types can be enabled by chaining mark_*() methods. The first one called becomes the default view, or use show() to set a specific default tab.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
A pandas DataFrame containing the data to visualize. The DataFrame should have columns for time/x-axis, values/y-axis, and optionally entities for grouping.
TYPE:
|
Example
import pandas as pd
from owid.grapher import Chart
df = pd.DataFrame({
'year': [2020, 2021, 2022],
'country': ['USA', 'China', 'India'],
'gdp': [21.4, 14.7, 2.9]
})
# Single chart type
Chart(df).mark_line().encode(
x='year',
y='gdp',
entity='country'
).label(
title='GDP by Country'
)
# Multiple chart types with bar as default
Chart(df).mark_line().mark_bar().show("discrete-bar").encode(...)
Source code in owid/grapher/__init__.py
encode ¶
encode(
x: Optional[str] = None,
y: Optional[str] = None,
y_lower: Optional[str] = None,
y_upper: Optional[str] = None,
entity: Optional[str] = None,
color: Optional[str] = None,
size: Optional[str] = None,
) -> Chart
Map DataFrame columns to visual properties.
This method establishes the visual encoding by mapping DataFrame columns to chart dimensions. The behavior varies by chart type:
- Line/Bar charts:
xis time,yis values,entitygroups lines/bars - Scatter plots:
xandyare both numeric values,entitygroups points
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Column name for x-axis. For line/bar charts, typically a time column ('year', 'date'). For scatter plots, a numeric value column.
TYPE:
|
y
|
Column name for y-axis values to plot. For bar charts, can be the entity column if you want entities on the y-axis.
TYPE:
|
y_lower
|
Column name for lower bound of confidence interval. When specified along with y_upper, renders a shaded confidence band around the main line.
TYPE:
|
y_upper
|
Column name for upper bound of confidence interval. When specified along with y_lower, renders a shaded confidence band around the main line.
TYPE:
|
entity
|
Column name for grouping data (e.g., 'country', 'region'). Each unique value becomes a separate line/series. Optional for single-series charts.
TYPE:
|
color
|
Column name for color encoding in scatter plots. Values map to colors.
TYPE:
|
size
|
Column name for size encoding in scatter plots. Values map to point sizes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
| RAISES | DESCRIPTION |
|---|---|
|
If a specified column name is not found in the DataFrame. |
Example
# Line chart with multiple countries
Chart(df).mark_line().encode(
x='year',
y='population',
entity='country'
)
# Line chart with confidence intervals
Chart(df).mark_line().encode(
x='year',
y='temperature',
y_lower='temperature_low',
y_upper='temperature_high',
entity='region'
)
# Scatter plot with color and size
Chart(df).mark_scatter().encode(
x='gdp_per_capita',
y='life_expectancy',
entity='country',
color='continent',
size='population'
)
Source code in owid/grapher/__init__.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
label ¶
Add labels and text to the chart.
| PARAMETER | DESCRIPTION |
|---|---|
title
|
Chart title.
TYPE:
|
subtitle
|
Chart subtitle.
TYPE:
|
source_desc
|
Data source attribution.
TYPE:
|
note
|
Additional notes or footnotes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
xaxis ¶
xaxis(
label: Optional[str] = None,
unit: Optional[str] = None,
scale: Optional[Literal["linear", "log"]] = None,
scale_control: Optional[bool] = None,
) -> Chart
Configure the x-axis.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
Axis label text.
TYPE:
|
unit
|
Unit of measurement (e.g., '$', 'kg').
TYPE:
|
scale
|
Scale type ('linear' or 'log').
TYPE:
|
scale_control
|
Allow users to toggle scale.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
yaxis ¶
yaxis(
label: Optional[str] = None,
unit: Optional[str] = None,
scale: Optional[Literal["linear", "log"]] = None,
scale_control: Optional[bool] = None,
) -> Chart
Configure the y-axis.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
Axis label text.
TYPE:
|
unit
|
Unit of measurement (e.g., '$', 'kg').
TYPE:
|
scale
|
Scale type ('linear' or 'log').
TYPE:
|
scale_control
|
Allow users to toggle scale.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
axis ¶
axis(
x_label: Optional[str] = None,
y_label: Optional[str] = None,
x_unit: Optional[str] = None,
y_unit: Optional[str] = None,
x_scale: Optional[Literal["linear", "log"]] = None,
y_scale: Optional[Literal["linear", "log"]] = None,
x_scale_control: Optional[bool] = None,
y_scale_control: Optional[bool] = None,
) -> Chart
Configure both axes at once.
Convenience method for setting properties on both axes. For single-axis configuration, use xaxis() or yaxis() instead.
| PARAMETER | DESCRIPTION |
|---|---|
x_label
|
Label text for x-axis.
TYPE:
|
y_label
|
Label text for y-axis.
TYPE:
|
x_unit
|
Unit suffix for x-axis values (e.g., '$', '%', 'kg').
TYPE:
|
y_unit
|
Unit suffix for y-axis values.
TYPE:
|
x_scale
|
Scale type for x-axis ('linear' or 'log').
TYPE:
|
y_scale
|
Scale type for y-axis ('linear' or 'log').
TYPE:
|
x_scale_control
|
If True, adds UI control to toggle x-axis scale.
TYPE:
|
y_scale_control
|
If True, adds UI control to toggle y-axis scale.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_scatter ¶
Add scatter plot to available chart types.
Scatter plots display individual data points with x and y positions. Use color
and size encodings for additional dimensions. Best for showing relationships
between two numeric variables.
Can be combined with other mark_*() methods to enable multiple chart types.
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_line ¶
Add line chart to available chart types.
Line charts connect data points with lines, ideal for showing trends over time. Multiple entities create multiple lines.
Can be combined with other mark_*() methods to enable multiple chart types.
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_bar ¶
Add bar chart to available chart types.
Bar charts display categorical data with rectangular bars. Bars can be shown side-by-side (default) or stacked on top of each other.
Can be combined with other mark_*() methods to enable multiple chart types.
| PARAMETER | DESCRIPTION |
|---|---|
stacked
|
If True, creates a stacked bar chart where bars for different entities are stacked vertically. If False (default), bars are shown side-by-side.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_slope ¶
Add slope chart to available chart types.
Slope charts compare values between two time points, showing the change as connecting lines between start and end values. Ideal for highlighting increases and decreases across entities.
Can be combined with other mark_*() methods to enable multiple chart types.
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_marimekko ¶
Add Marimekko chart to available chart types.
Marimekko charts (also called mosaic charts) show part-to-whole relationships where both width and height of segments are meaningful. Width represents one dimension (e.g., population) and height represents another (e.g., percentage).
Can be combined with other mark_*() methods to enable multiple chart types.
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
mark_map ¶
mark_map(
time_tolerance: Optional[int] = None,
color_scheme: Optional[ColorSchemeName] = None,
binning_strategy: Optional[BinningStrategy] = None,
custom_numeric_values: Optional[List[float]] = None,
) -> Chart
Enable the map tab with optional configuration.
Adds a world map visualization showing data geographically. Can be combined with other mark_*() methods.
| PARAMETER | DESCRIPTION |
|---|---|
time_tolerance
|
How many years to look back/forward for data
TYPE:
|
color_scheme
|
Color scheme name (e.g., "Reds", "Blues", "YlOrRd")
TYPE:
|
binning_strategy
|
How to bin values ("auto", "manual", "equalInterval", "quantiles")
TYPE:
|
custom_numeric_values
|
Custom bin boundaries when using manual binning
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Example
Source code in owid/grapher/__init__.py
show ¶
show(
tab: Literal[
"line",
"discrete-bar",
"stacked-discrete-bar",
"scatter",
"stacked-area",
"slope",
"stacked-bar",
"marimekko",
"map",
"table",
],
) -> Chart
Set which tab to display by default.
Use this to control which visualization is shown when the chart first loads. The tab must correspond to an enabled chart type (via mark_*() methods).
| PARAMETER | DESCRIPTION |
|---|---|
tab
|
The tab to show by default. Options: - "line": Line chart - "discrete-bar": Bar chart - "stacked-discrete-bar": Stacked bar chart - "scatter": Scatter plot - "map": World map - "table": Data table
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Example
Source code in owid/grapher/__init__.py
interact ¶
interact(
allow_relative: Optional[bool] = None,
scale_control: Optional[bool] = None,
entity_control: Optional[bool] = None,
entity_mode: Optional[EntitySelectionMode] = None,
) -> Chart
Add interactive controls to the chart.
| PARAMETER | DESCRIPTION |
|---|---|
allow_relative
|
Show relative/absolute toggle.
TYPE:
|
scale_control
|
Show log/linear scale toggle.
TYPE:
|
entity_control
|
Show entity/country picker (shorthand for entity_mode).
TYPE:
|
entity_mode
|
Entity selection mode. Options: - "add-country": Allow adding multiple entities (default when entity_control=True) - "change-country": Allow only single entity selection (useful for charts with multiple lines per entity, e.g., confidence intervals) - "disabled": Disable entity selection
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
select ¶
select(
entities: Optional[List[str]] = None,
timespan: Optional[Tuple[Any, Any]] = None,
) -> Chart
Pre-select entities and time range.
| PARAMETER | DESCRIPTION |
|---|---|
entities
|
List of entity names to display.
TYPE:
|
timespan
|
Tuple of (start, end) for time range.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
transform ¶
Transform data to relative or absolute values.
Display values as percentage change from a baseline (relative mode) or as absolute values (default). In relative mode, the first time period serves as the baseline (100%).
| PARAMETER | DESCRIPTION |
|---|---|
relative
|
If True, show values as percentage change from baseline. If False, show absolute values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
filter ¶
Filter entities to only show those with complete data.
When enabled, only entities that have data for all time periods and dimensions will be shown. Useful for ensuring fair comparisons by excluding entities with incomplete data.
| PARAMETER | DESCRIPTION |
|---|---|
matching_entities_only
|
If True, only show entities with complete data across all dimensions and time periods. If False, show all entities even with gaps.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Source code in owid/grapher/__init__.py
variable ¶
variable(
column: str,
name: Optional[str] = None,
description_short: Optional[str] = None,
description_from_producer: Optional[str] = None,
description_processing: Optional[str] = None,
description_key: Optional[List[str]] = None,
unit: Optional[str] = None,
short_unit: Optional[str] = None,
color: Optional[str] = None,
source_name: Optional[str] = None,
source_link: Optional[str] = None,
) -> Chart
Add rich metadata to a data column/variable.
Configures display properties and documentation for a column that will appear in tooltips, the data table, and source information.
| PARAMETER | DESCRIPTION |
|---|---|
column
|
Name of the DataFrame column to configure.
TYPE:
|
name
|
Display name (e.g., "Population" instead of "pop").
TYPE:
|
description_short
|
Brief description shown in tooltips.
TYPE:
|
description_from_producer
|
Original description from data source.
TYPE:
|
description_processing
|
How the data was processed/transformed.
TYPE:
|
description_key
|
List of key points about the variable.
TYPE:
|
unit
|
Full unit name (e.g., "million people").
TYPE:
|
short_unit
|
Abbreviated unit for compact display (e.g., "M").
TYPE:
|
color
|
Hex color for the line/series (e.g., "#ca2628").
TYPE:
|
source_name
|
Name of the data source.
TYPE:
|
source_link
|
URL to the data source.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Self for method chaining. |
Note
The timespan is computed automatically from the data's time column.
Example
Source code in owid/grapher/__init__.py
export ¶
Export the chart as the three components needed for rendering.
| RETURNS | DESCRIPTION |
|---|---|
|
Dictionary with keys: - csv_data: CSV string of the data - column_defs: List of column definition dicts for OwidTable - grapher_config: Dict of GrapherState configuration |
Source code in owid/grapher/__init__.py
save_png ¶
Save the chart as a PNG image.
This method uses Playwright to render the chart in a headless browser and export it using the Grapher's built-in rasterize function.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to save the PNG.
TYPE:
|
include_details
|
Whether to include chart details/sources in export.
TYPE:
|
timeout
|
Timeout in milliseconds for rendering.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
|
If Playwright is not installed. Install with: pip install playwright && playwright install chromium |
Example
Source code in owid/grapher/__init__.py
save_svg ¶
Save the chart as an SVG image.
This method uses Playwright to render the chart in a headless browser and export it using the Grapher's built-in rasterize function.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path to save the SVG.
TYPE:
|
include_details
|
Whether to include chart details/sources in export.
TYPE:
|
timeout
|
Timeout in milliseconds for rendering.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
|
If Playwright is not installed. Install with: pip install playwright && playwright install chromium |
Example
Source code in owid/grapher/__init__.py
to_html ¶
Return the full HTML page for this chart.
This returns a complete HTML document that can be: - Saved to a file and opened in a browser - Embedded in an iframe on a webpage - Used for custom rendering scenarios
| RETURNS | DESCRIPTION |
|---|---|
|
Complete HTML document string. |
Example
Source code in owid/grapher/__init__.py
owid.grapher.TimeType ¶
Bases:
Enumeration for time dimension types.
Determines how time values are interpreted and displayed in charts.
| ATTRIBUTE | DESCRIPTION |
|---|---|
|
Daily or date-based data. Automatically detected when x='date'. Uses ISO date format (YYYY-MM-DD).
|
|
Annual data (default). Standard yearly time series.
|