## File: README.md # Vega-Altair [](https://altair-viz.github.io/) [](https://github.com/vega/altair/actions?query=workflow%3Abuild) [](https://www.mypy-lang.org) [](https://joss.theoj.org/papers/10.21105/joss.01057) [](https://pypi.org/project/altair) **Vega-Altair** is a declarative statistical visualization library for Python. With Vega-Altair, you can spend more time understanding your data and its meaning. Vega-Altair's API is simple, friendly and consistent and built on top of the powerful [Vega-Lite](https://github.com/vega/vega-lite) JSON specification. This elegant simplicity produces beautiful and effective visualizations with a minimal amount of code. *Vega-Altair was originally developed by [Jake Vanderplas](https://github.com/jakevdp) and [Brian Granger](https://github.com/ellisonbg) in close collaboration with the [UW Interactive Data Lab](https://idl.cs.washington.edu/).* *The Vega-Altair open source project is not affiliated with Altair Engineering, Inc.* ## Documentation See [Vega-Altair's Documentation Site](https://altair-viz.github.io) as well as the [Tutorial Notebooks](https://github.com/altair-viz/altair_notebooks). You can run the notebooks directly in your browser by clicking on one of the following badges: [](https://beta.mybinder.org/v2/gh/altair-viz/altair_notebooks/master) [](https://colab.research.google.com/github/altair-viz/altair_notebooks/blob/master/notebooks/Index.ipynb) ## Example Here is an example using Vega-Altair to quickly visualize and display a dataset with the native Vega-Lite renderer in the JupyterLab: ```python import altair as alt # load a simple dataset as a pandas DataFrame from altair.datasets import data cars = data.cars() alt.Chart(cars).mark_point().encode( x="Horsepower", y="Miles_per_Gallon", color="Origin", ) ``` One of the unique features of Vega-Altair, inherited from Vega-Lite, is a declarative grammar of not just visualization, but _interaction_. With a few modifications to the example above we can create a linked histogram that is filtered based on a selection of the scatter plot. ```python import altair as alt from altair.datasets import data source = data.cars() brush = alt.selection_interval() points = alt.Chart(source).mark_point().encode( x="Horsepower", y="Miles_per_Gallon", color=alt.when(brush).then("Origin").otherwise(alt.value("lightgray")), ).add_params( brush ) bars = alt.Chart(source).mark_bar().encode( x="count(Origin)", y="Origin", color="Origin", ).transform_filter( brush ) points & bars ``` ## Features - Carefully-designed, declarative Python API. - Auto-generated internal Python API that guarantees visualizations are type-checked and in full conformance with the [Vega-Lite](https://github.com/vega/vega-lite) specification. - Display visualizations in JupyterLab, Jupyter Notebook, Visual Studio Code, on GitHub and [nbviewer](https://nbviewer.jupyter.org/), and many more. - Export visualizations to various formats such as PNG/SVG images, stand-alone HTML pages and the [Online Vega-Lite Editor](https://vega.github.io/editor/#/). - Serialize visualizations as JSON files. ## Installation Vega-Altair can be installed with: ```bash pip install altair ``` If you are using the conda package manager, the equivalent is: ```bash conda install altair -c conda-forge ``` For full installation instructions, please see [the documentation](https://altair-viz.github.io/getting_started/installation.html). ## Getting Help If you have a question that is not addressed in the documentation, you can post it on [StackOverflow](https://stackoverflow.com/questions/tagged/altair) using the `altair` tag. For bugs and feature requests, please open a [Github Issue](https://github.com/vega/altair/issues). ## Development [](https://github.com/astral-sh/uv) [](https://github.com/astral-sh/ruff) [](https://github.com/pytest-dev/pytest) For information on how to contribute your developments back to the Vega-Altair repository, see [`CONTRIBUTING.md`](https://github.com/vega/altair/blob/main/CONTRIBUTING.md) ## Citing Vega-Altair [](https://joss.theoj.org/papers/10.21105/joss.01057) If you use Vega-Altair in academic work, please consider citing https://joss.theoj.org/papers/10.21105/joss.01057 as ```bib @article{VanderPlas2018, doi = {10.21105/joss.01057}, url = {https://doi.org/10.21105/joss.01057}, year = {2018}, publisher = {The Open Journal}, volume = {3}, number = {32}, pages = {1057}, author = {Jacob VanderPlas and Brian Granger and Jeffrey Heer and Dominik Moritz and Kanit Wongsuphasawat and Arvind Satyanarayan and Eitan Lees and Ilia Timofeev and Ben Welsh and Scott Sievert}, title = {Altair: Interactive Statistical Visualizations for Python}, journal = {Journal of Open Source Software} } ``` Please additionally consider citing the [Vega-Lite](https://vega.github.io/vega-lite/) project, which Vega-Altair is based on: https://dl.acm.org/doi/10.1109/TVCG.2016.2599030 ```bib @article{Satyanarayan2017, author={Satyanarayan, Arvind and Moritz, Dominik and Wongsuphasawat, Kanit and Heer, Jeffrey}, title={Vega-Lite: A Grammar of Interactive Graphics}, journal={IEEE transactions on visualization and computer graphics}, year={2017}, volume={23}, number={1}, pages={341-350}, publisher={IEEE} } ``` --- ## File: altair/jupyter/js/README.md # JupyterChart This directory contains the JavaScript portion of the Altair `JupyterChart`. The `JupyterChart` is based on the [AnyWidget](https://anywidget.dev/) project. --- ## File: doc/_templates/class.rst :mod:`{{module}}`.{{objname}} {{ underline }}============== .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} {% block methods %} .. automethod:: __init__ {% endblock %} .. raw:: html --- ## File: doc/about/citing.rst Citing =============== Vega-Altair ----------- If you use Vega-Altair in academic work, please consider citing `Altair: Interactive Statistical Visualizations for Python `_ as .. code-block:: @article{VanderPlas2018, doi = {10.21105/joss.01057}, url = {https://doi.org/10.21105/joss.01057}, year = {2018}, publisher = {The Open Journal}, volume = {3}, number = {32}, pages = {1057}, author = {Jacob VanderPlas and Brian Granger and Jeffrey Heer and Dominik Moritz and Kanit Wongsuphasawat and Arvind Satyanarayan and Eitan Lees and Ilia Timofeev and Ben Welsh and Scott Sievert}, title = {Altair: Interactive Statistical Visualizations for Python}, journal = {Journal of Open Source Software} } Vega-Lite --------- Please additionally consider citing the `Vega-Lite `_ project, which Vega-Altair is based on: `Vega-Lite: A Grammar of Interactive Graphics `_ .. code-block:: @article{Satyanarayan2017, author={Satyanarayan, Arvind and Moritz, Dominik and Wongsuphasawat, Kanit and Heer, Jeffrey}, title={Vega-Lite: A Grammar of Interactive Graphics}, journal={IEEE transactions on visualization and computer graphics}, year={2017}, volume={23}, number={1}, pages={341-350}, publisher={IEEE} } --- ## File: doc/about/code_of_conduct.rst Code of Conduct =============== As a project of the Vega Organization, we use the `Vega Code of Conduct `_. --- ## File: doc/about/governance.rst Governance ========== Vega-Altair's governance structure is based on GitHub's `Minimum Viable Governance `_ (MVG) template. Organizational Governance ------------------------- The Altair-Viz organization is governed by the documents that reside in the `Vega Organizational GitHub repository `_. Project Governance ------------------ The Vega-Altair library is governed by the documents that reside in the `project-docs `_ directory of the Vega Organizational GitHub repository. --- ## File: doc/about/roadmap.rst Roadmap ======= The roadmap for Vega-Altair and related projects can be found in `this project board `_. .. toctree:: :maxdepth: 1 :caption: About :hidden: self code_of_conduct governance citing versioning --- ## File: doc/about/versioning.rst Versioning ========== Vega-Altair has historically released major versions that coincide with those of Vega-Lite_. As the projects have matured, and major versions become less frequent, there has been a growing need to introduce breaking changes between these major versions. Such changes would allow Vega-Altair to address technical debt and improve upon API ergonomics. To ensure future releases clearly communicate changes, Vega-Altair will be working towards adopting SemVer_. Public API ---------- Functionality documented in :ref:`api` defines the Vega-Altair public API. Version numbers --------------- A Vega-Altair release number is composed of ``MAJOR.MINOR.PATCH``. * Backward incompatible API changes increment **MAJOR** version (``4.2.2`` - ``5.0.0``) * New backward compatible functionality increment **MINOR** version (``5.2.0`` - ``5.3.0``) * Backward compatible bug fixes increment **PATCH** version (``5.1.1`` - ``5.1.2``) **MAJOR** versions will *likely* continue to increase with a **MAJOR** increment to Vega-Lite_. Deprecation ----------- Deprecation warnings may be introduced in **MAJOR** and **MINOR** versions, but the removal of deprecated functionality will not occur until *at least* the next **MAJOR** version. For upstream breaking changes that trigger a **MAJOR** version, we *may* provide a deprecation warning if we consider the change especially disruptive. Starting in version ``5.4.0``, all deprecation warnings *must* specify: * the version number they were introduced Where possible, deprecation warnings *may* specify: * an alternative function/method/parameter/class to use instead * an explanation for why this change had to be made Deprecated functionality *may* be removed from the Vega-Altair documentation, if there is a suitable replacement and we believe inclusion of both could confuse new users. .. _Vega-Lite: https://github.com/vega/vega-lite .. _SemVer: https://semver.org/ --- ## File: doc/case_studies/exploring-weather.rst .. _exploring-weather: Exploring Seattle Weather ------------------------- (This tutorial is adapted from `Vega-Lite's documentation `_) In this tutorial, you’ll learn a few more techniques for creating visualizations in Altair. If you are not familiar with Altair, please read :ref:`starting` first. For this tutorial, we will create visualizations to explore weather data for Seattle, taken from NOAA. The dataset is a CSV file with columns for the temperature (in Celsius), precipitation (in millimeters), wind speed (in meter/second), and weather type. We have one row for each day from January 1st, 2012 to December 31st, 2015. Altair is designed to work with data in the form of pandas_ dataframes, and contains a loader for this and other built-in datasets: .. altair-plot:: :output: repr from altair.datasets import data df = data.seattle_weather() df.head() The data is loaded from the web and stored in a pandas DataFrame, and from here we can explore it with Altair. Let’s start by looking at the precipitation, using tick marks to see the distribution of precipitation values: .. altair-plot:: import altair as alt alt.Chart(df).mark_tick().encode( x='precipitation', ) It looks as though precipitation is skewed towards lower values; that is, when it rains in Seattle, it usually doesn’t rain very much. It is difficult to see patterns across continuous variables, and so to better see this, we can create a histogram of the precipitation data. For this we first discretize the precipitation values by adding a binning to ``x``. Additionally, we set our encoding channel ``y`` with ``count``. The result is a histogram of precipitation values: .. altair-plot:: alt.Chart(df).mark_bar().encode( alt.X('precipitation').bin(), y='count()' ) Next, let’s look at how precipitation in Seattle changes throughout the year. Altair natively supports dates and discretization of dates when we set the type to ``temporal`` (shorthand ``T``). For example, in the following plot, we compute the total precipitation for each month. To discretize the data into months, we can use a ``month`` binning (see :ref:`user-guide-timeunit-transform` for more information about this and other ``timeUnit`` binnings): .. altair-plot:: alt.Chart(df).mark_line().encode( x='month(date):T', y='average(precipitation)' ) This chart shows that in Seattle the precipitation in the winter is, on average, much higher than summer (an unsurprising observation to those who live there!). By changing the mapping of encoding channels to data features, you can begin to explore the relationships within the data. When looking at precipitation and temperature, we might want to aggregate by year *and* month (``yearmonth``) rather than just month. This allows us to see seasonal trends, with daily variation smoothed out. We might also wish to see the maximum and minimum temperature in each month: .. altair-plot:: alt.Chart(df).mark_line().encode( x='yearmonth(date):T', y='max(temp_max)', ) In this chart, it looks as though the maximum temperature is increasing from year to year over the course of this relatively short baseline. To look closer into this, let’s instead look at the mean of the maximum daily temperatures for each year: .. altair-plot:: alt.Chart(df).mark_line().encode( x='year(date):T', y='mean(temp_max)', ) This can be a little clearer if we use a bar plot and mark the year as an "ordinal" (ordered category) type. For aesthetic reasons, let's make the bar chart horizontal by assigning the ordinal value to the y-axis: .. altair-plot:: alt.Chart(df).mark_bar().encode( x='mean(temp_max)', y='year(date):O' ) The chart indicates that the annual average of the daily high temperatures increased over the course of these four years, a fact that you can confirm for minimum daily temperatures as well. You might also wonder how the daily temperature range changes throughout the year. For this, we have to add a computation to derive a new field, which can be done by adding a ``calculate`` transform: .. altair-plot:: alt.Chart(df).mark_bar().encode( x='mean(temp_range):Q', y='year(date):O' ).transform_calculate( temp_range="datum.temp_max - datum.temp_min" ) Note that this calculation doesn't actually do any data manipulation in Python, but rather encodes and stores the operations within the plot specification, where they will be calculated by the renderer. Of course, the same calculation could be done by using pandas manipulations to explicitly add a column to the dataframe; the disadvantage there is that the derived values would have to be stored in the plot specification rather than computed on-demand in the browser. Next we will explore the ``weather`` field, which encodes a categorical variable describing the weather on a given day. We might wish to know how different kinds of weather (e.g. sunny days or rainy days) are distributed throughout the year. To answer this, we can discretize the date by month and then count the number of records on the y-Axis. We then break down the bars by the weather type by mapping this column to a color channel. When a bar chart has a field mapped to color, Altair will automatically stack the bars atop each other: .. altair-plot:: alt.Chart(df).mark_bar().encode( x='month(date):N', y='count()', color='weather', ) The default color palette’s semantics might not match our expectation. For example, we probably do not expect “sun” (sunny) to be purple. We can tune the chart by providing a color scale range that maps the values from the weather field to meaningful colors, using standard hex color codes: .. altair-plot:: :output: none scale = alt.Scale(domain=['sun', 'fog', 'drizzle', 'rain', 'snow'], range=['#e7ba52', '#c7c7c7', '#aec7e8', '#1f77b4', '#9467bd']) This scale can be passed to the color encoding to be applied to the plot style. In addition, we can customize the titles for the axis and legend to make the meaning of the plot more clear: .. altair-plot:: alt.Chart(df).mark_bar().encode( x=alt.X('month(date):N').title('Month of the year'), y='count()', color=alt.Color('weather', legend=alt.Legend(title='Weather type'), scale=scale), ) Combining the above ideas lets us create any number of flexible visualizations of this dataset. For example, here is a plot that uses the customizations we have developed above to explore the relationship between weather, precipitation, maximum temperature, and temperature range, configured to use a larger canvas and to allow interactive panning and zooming with the mouse: .. altair-plot:: alt.Chart(df).mark_point().encode( alt.X('temp_max').title('Maximum Daily Temperature (C)'), alt.Y('temp_range:Q').title('Daily Temperature Range (C)'), alt.Color('weather').scale(scale), alt.Size('precipitation').scale(range=[1, 200]) ).transform_calculate( "temp_range", "datum.temp_max - datum.temp_min" ).properties( width=600, height=400 ).interactive() This gives us even more insight into the weather patterns in Seattle: rainy and foggy days tend to be cooler with a narrower range of temperatures, while warmer days tend to be dry and sunny, with a wider spread between low and high temperature. You can take this even further using Altair's building blocks for multi-panel charts and interactions. For example, we might construct a histogram of days by weather type: .. altair-plot:: alt.Chart(df).mark_bar().encode( x='count()', y='weather:N', color=alt.Color('weather:N').scale(scale), ) And now we can vertically concatenate this histogram to the points plot above, and add a brush selection tool such that the histogram reflects the content of the selection (for more information on selections, see :ref:`user-guide-interactions`): .. altair-plot:: brush = alt.selection_interval() color = alt.Color("weather:N").scale(scale) temp_range = alt.datum["temp_max"] - alt.datum["temp_min"] points = alt.Chart(width=600, height=400).mark_point().encode( alt.X("temp_max:Q").title("Maximum Daily Temperature (C)"), alt.Y("temp_range:Q").title("Daily Temperature Range (C)"), color=alt.when(brush).then(color).otherwise(alt.value("lightgray")), size=alt.Size("precipitation:Q").scale(range=[1, 200]), ).transform_calculate( temp_range=temp_range ).add_params( brush ) bars = alt.Chart(width=600).mark_bar().encode( x="count()", y="weather:N", color=color ).transform_calculate( temp_range=temp_range ).transform_filter( brush ) alt.vconcat(points, bars, data=df) This chart, containing concatenations, data transformations, selections, and customized axes labels and data scales, shows the power of the grammar behind Altair: you can create a complex chart from a small number of building blocks. This is the end of this tutorial where you have seen various ways to bin and aggregate data, derive new fields, and customize your charts. You can find more visualizations in the :ref:`example-gallery`. If you want to further customize your charts, you can refer to Altair's :ref:`api`. .. _pandas: http://pandas.pydata.org/ --- ## File: doc/case_studies/index.rst Tutorials --------- These tutorials explore more advanced use cases than the gallery. .. toctree:: :hidden: exploring-weather numpy-tooltip-images