Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Altair Debugging Guide

In this notebook we show you common debugging techniques that you can use if you run into issues with Altair.

You can jump to the following sections:

In addition to this notebook, you might find the Frequently Asked Questions and Display Troubleshooting guides helpful.

This notebook is part of the data visualization curriculum.

Installation

These instructions follow the Altair documentation but focus on some specifics for this series of notebooks.

In every notebook, we will import the Altair and Vega Datasets packages. If you are running this notebook on Colab, Altair and Vega Datasets should be preinstalled and ready to go. The notebooks in this series are designed for Colab but should also work in Jupyter Lab or the Jupyter Notebook (the notebook requires a bit more setup described below) but additional packages are required.

If you are running in Jupyter Lab or Jupyter Notebooks, you have to install the necessary packages by running the following command in your terminal.

pip install altair vega_datasets

Or if you use Conda

conda install -c conda-forge altair vega_datasets

You can run command line commands from a code cell by prefixing it with !. For example, to install Altair and Vega Datasets with Pip, you can run the following cell.

!pip install altair vega_datasets
/bin/bash: pip: command not found
import altair as alt
from altair.datasets import data

Make sure you are Using the Latest Version of Altair

If you are running into issues with Altair, first make sure that you are running the latest version. To check the version of Altair that you have installed, run the cell below.

alt.__version__
'6.0.0'

To check what the latest version of altair is, go to this page or run the cell below (requires Python 3).

import urllib.request, json 
with urllib.request.urlopen("https://pypi.org/pypi/altair/json") as url:
    print(json.loads(url.read().decode())['info']['version'])
6.0.0

If you are not running the latest version, you can update it with pip. You can update Altair and Vega Datasets by running this command in your terminal.

pip install -U altair vega_datasets

Try Making a Chart

Now you can create an Altair chart.

cars = data.cars()

alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Displacement',
    color='Origin'
)
Loading...

Special Setup for the Jupyter Notebook

If you are running in Jupyter Lab, Jupyter Notebook, or Colab (and have a working Internet connection) you should be seeing a chart. If you are running in another environment (or offline), you will need to tell Altair to use a different renderer;

To activate a different renderer in a notebook cell:

# to run in nteract, VSCode, or offline in JupyterLab
alt.renderers.enable('mimebundle')

To run offline in Jupyter Notebook you must install an additional dependency, the vega package. Run this command in your terminal:

pip install vega

Then activate the notebook renderer:

# to run offline in Jupyter Notebook
alt.renderers.enable('notebook')

These instruction follow the instructions on the Altair website.

Display Troubleshooting

If you are having issues with seeing a chart, make sure your setup is correct by following the debugging instruction above. If you are still having issues, follow the instruction about debugging display issues in the Altair documentation.

Non Existent Fields

A common error is accidentally using a field that does not exist.

import pandas as pd

df = pd.DataFrame({'x': [1, 2, 3],
                     'y': [3, 1, 4]})

alt.Chart(df).mark_point().encode(
    x='x:Q',
    y='y:Q',
    color='color:Q'  # <-- this field does not exist in the data!
)
Loading...

Check the spelling of your files and print the data source to confirm that the data and fields exist. For instance, here you see that color is not a valid field.

df.head()
Loading...

Invalid Specifications

Another common issue is creating an invalid specification and getting an error.

Invalid Properties

Altair might show an SchemaValidationError or ValueError. Read the error message carefully. Usually it will tell you what is going wrong.

For example, if you forget the mark type, you will see this SchemaValidationError.

alt.Chart(cars).encode(
    y='Horsepower'
)
---------------------------------------------------------------------------
SchemaValidationError                     Traceback (most recent call last)
File ~/altair/.venv/lib/python3.13/site-packages/altair/vegalite/v6/api.py:3801, in TopLevelMixin._repr_mimebundle_(self, *args, **kwds)
   3798 # Catch errors explicitly to get around issues in Jupyter frontend
   3799 # see https://github.com/ipython/ipython/issues/11038
   3800 try:
-> 3801     dct = self.to_dict(context={"pre_transform": False})
   3802 except Exception:
   3803     utils.display_traceback(in_ipython=True)

File ~/altair/.venv/lib/python3.13/site-packages/altair/vegalite/v6/api.py:4173, in Chart.to_dict(self, validate, format, ignore, context)
   4171     copy.data = core.InlineData(values=[{}])
   4172     return super(Chart, copy).to_dict(**kwds)
-> 4173 return super().to_dict(**kwds)

File ~/altair/.venv/lib/python3.13/site-packages/altair/vegalite/v6/api.py:2121, in TopLevelMixin.to_dict(self, validate, format, ignore, context)
   2118 # remaining to_dict calls are not at top level
   2119 context["top_level"] = False
-> 2121 vegalite_spec: Any = _top_schema_base(super(TopLevelMixin, copy)).to_dict(
   2122     validate=validate, ignore=ignore, context=dict(context, pre_transform=False)
   2123 )
   2125 # TODO: following entries are added after validation. Should they be validated?
   2126 if is_top_level:
   2127     # since this is top-level we add $schema if it's missing

File ~/altair/.venv/lib/python3.13/site-packages/altair/utils/schemapi.py:1238, in SchemaBase.to_dict(self, validate, ignore, context)
   1236         self.validate(result)
   1237     except jsonschema.ValidationError as err:
-> 1238         raise SchemaValidationError(self, err) from None
   1239 return result

SchemaValidationError: '{'data': {'name': 'data-ad3a0dd023cd6593db8ec56326f31fcb'}, 'encoding': {'y': {'field': 'Horsepower', 'type': 'quantitative'}}}' is an invalid value.

'mark' is a required property
alt.Chart(...)

Or if you use a non-existent channel, you get a ValueError.

alt.Chart(cars).mark_point().encode(
    z='Horsepower'
)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 alt.Chart(cars).mark_point().encode(
      2     z='Horsepower'
      3 )

TypeError: _EncodingMixin.encode() got an unexpected keyword argument 'z'

Properties are Being Ignored

Altair might ignore a property that you specified. In the chart below, we are using a text channel, which is only compatible with mark_text. You do not see an error or a warning about this in the notebook. However, the underlying Vega-Lite library will show a warning in the browser console. Press Alt+Cmd+I on Mac or Alt+Ctrl+I on Windows and Linux to open the developer tools and click on the Console tab. When you run the example in the cell below, you will see a the following warning.

WARN text dropped as it is incompatible with "bar".
alt.Chart(cars).mark_bar().encode(
    y='mean(Horsepower)',
    text='mean(Acceleration)'
)
Loading...

If you find yourself debugging issues related to Vega-Lite, you can open the chart in the Vega Editor either by clicking on the “Open in Vega Editor” link at the bottom of the chart or in the action menu (click to open) at the top right of a chart. The Vega Editor provides additional debugging but you will be writing Vega-Lite JSON instead of Altair in Python.

Note: The Vega Editor may be using a newer version of Vega-Lite and so the behavior may vary.

Asking for Help

If you find a problem with Altair and get stuck, you can ask a question on Stack Overflow. Ask your question with the altair and vega-lite tags. You can find a list of questions people have asked before here.

Reporting Issues

If you find a problem with Altair and believe it is a bug, please create an issue in the Altair GitHub repo with a description of your problem. If you believe the issue is related to the underlying Vega-Lite library, please create an issue in the Vega-Lite GitHub repo.