Altairデバッグガイド#

このノートブックでは、Altairに関連する問題が発生した場合に役立つ一般的なデバッグ技法を紹介します。

以下のセクションにジャンプできます:

このノートブックに加えて、よくある質問表示のトラブルシューティングガイドも役立つかもしれません。

このノートブックはデータ可視化カリキュラムの一部です。

Installation#

これらの手順はAltairのドキュメントに従っていますが、この一連のノートブックに特有の内容に焦点を当てています。

すべてのノートブックで、AltairVega Datasetsパッケージをインポートします。Colabでこのノートブックを実行している場合、AltairとVega Datasetsはあらかじめインストールされており、そのまま使用できます。このシリーズのノートブックはColab用に設計されていますが、Jupyter LabやJupyter Notebookでも動作するはずです(Jupyter Notebookの場合は下記の特別なセットアップが必要です)ただし、追加のパッケージが必要です。

Jupyter LabまたはJupyter Notebooksで実行している場合、以下のコマンドをターミナルで実行して必要なパッケージをインストールする必要があります。

pip install altair vega_datasets

Or if you use Conda

conda install -c conda-forge altair vega_datasets

コマンドラインコマンドは、コードセルの前に!を付けて実行できます。例えば、AltairとVega DatasetsをPipでインストールするには、以下のセルを実行できます。

!pip install altair vega_datasets
Requirement already satisfied: altair in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (5.2.0)
Requirement already satisfied: vega_datasets in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (0.9.0)
Requirement already satisfied: jinja2 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (3.1.2)
Requirement already satisfied: jsonschema>=3.0 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (4.16.0)
Requirement already satisfied: numpy in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (1.24.2)
Requirement already satisfied: packaging in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (23.0)
Requirement already satisfied: pandas>=0.25 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (1.5.3)
Requirement already satisfied: toolz in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (0.12.0)
Requirement already satisfied: typing-extensions>=4.0.1 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from altair) (4.9.0)
Requirement already satisfied: attrs>=17.4.0 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from jsonschema>=3.0->altair) (23.2.0)
Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from jsonschema>=3.0->altair) (0.18.1)
Requirement already satisfied: python-dateutil>=2.8.1 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from pandas>=0.25->altair) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from pandas>=0.25->altair) (2023.3.post1)
Requirement already satisfied: MarkupSafe>=2.0 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from jinja2->altair) (2.1.1)
Requirement already satisfied: six>=1.5 in /Users/yuichiyazaki/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages (from python-dateutil>=2.8.1->pandas>=0.25->altair) (1.16.0)
import altair as alt
from vega_datasets import data

Make sure you are Using the Latest Version of Altair#

コマンドラインコマンドは、コードセルの前に!を付けて実行できます。例えば、AltairとVega DatasetsをPipでインストールするには、以下のセルを実行できます。

alt.__version__
'5.2.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'])
5.5.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'
)

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!
)

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 vaid field.

df.head()
x y
0 1 3
1 2 1
2 3 4

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 ~/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages/altair/vegalite/v5/api.py:2975, in Chart.to_dict(self, validate, format, ignore, context)
   2971     copy.data = core.InlineData(values=[{}])  # type: ignore[assignment]
   2972     return super(Chart, copy).to_dict(
   2973         validate=validate, format=format, ignore=ignore, context=context
   2974     )
-> 2975 return super().to_dict(
   2976     validate=validate, format=format, ignore=ignore, context=context
   2977 )

File ~/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages/altair/vegalite/v5/api.py:961, in TopLevelMixin.to_dict(self, validate, format, ignore, context)
    956 context["top_level"] = False
    958 # TopLevelMixin instance does not necessarily have to_dict defined
    959 # but due to how Altair is set up this should hold.
    960 # Too complex to type hint right now
--> 961 vegalite_spec = super(TopLevelMixin, copy).to_dict(  # type: ignore[misc]
    962     validate=validate, ignore=ignore, context=dict(context, pre_transform=False)
    963 )
    965 # TODO: following entries are added after validation. Should they be validated?
    966 if is_top_level:
    967     # since this is top-level we add $schema if it's missing

File ~/.pyenv/versions/miniforge3-4.10.3-10/lib/python3.9/site-packages/altair/utils/schemapi.py:979, in SchemaBase.to_dict(self, validate, ignore, context)
    972         self.validate(result)
    973     except jsonschema.ValidationError as err:
    974         # We do not raise `from err` as else the resulting
    975         # traceback is very long as it contains part
    976         # of the Vega-Lite schema. It would also first
    977         # show the less helpful ValidationError instead of
    978         # the more user friendly SchemaValidationError
--> 979         raise SchemaValidationError(self, err) from None
    980 return result

SchemaValidationError: '{'data': {'name': 'data-f02450ab61490a1363517a0190416235'}, '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'
)
  Cell In [9], line 1
    alt.Chart(cars)).mark_point().encode(
                   ^
SyntaxError: unmatched ')'

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)'
)

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.