├── .github ├── ISSUE_TEMPLATE │ ├── bug-report.md │ ├── config.yml │ └── feature-request.md └── workflows │ ├── build.yml │ ├── docbuild.yml │ └── lint.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── Makefile ├── NOTES_FOR_MAINTAINERS.md ├── README.md ├── RELEASING.md ├── altair ├── __init__.py ├── _magics.py ├── datasets.py ├── examples │ ├── __init__.py │ ├── airport_connections.py │ ├── airports.py │ ├── airports_count.py │ ├── anscombe_plot.py │ ├── area_chart_gradient.py │ ├── bar_and_line_with_dual_axis.py │ ├── bar_chart_horizontal.py │ ├── bar_chart_sorted.py │ ├── bar_chart_trellis_compact.py │ ├── bar_chart_with_highlighted_bar.py │ ├── bar_chart_with_highlighted_segment.py │ ├── bar_chart_with_labels.py │ ├── bar_chart_with_mean_line.py │ ├── bar_chart_with_negatives.py │ ├── bar_rounded.py │ ├── bar_with_rolling_mean.py │ ├── beckers_barley_trellis_plot.py │ ├── beckers_barley_wrapped_facet.py │ ├── binned_heatmap.py │ ├── binned_scatterplot.py │ ├── boxplot.py │ ├── bubble_plot.py │ ├── bump_chart.py │ ├── candlestick_chart.py │ ├── choropleth.py │ ├── choropleth_repeat.py │ ├── co2_concentration.py │ ├── comet_chart.py │ ├── connected_scatterplot.py │ ├── cumulative_count_chart.py │ ├── cumulative_wiki_donations.py │ ├── density_facet.py │ ├── density_stack.py │ ├── diverging_stacked_bar_chart.py │ ├── donut_chart.py │ ├── dot_dash_plot.py │ ├── errorbars_with_ci.py │ ├── errorbars_with_std.py │ ├── falkensee.py │ ├── filled_step_chart.py │ ├── gantt_chart.py │ ├── gapminder_bubble_plot.py │ ├── grouped_bar_chart.py │ ├── grouped_bar_chart2.py │ ├── grouped_bar_chart_horizontal.py │ ├── grouped_bar_chart_with_error_bars.py │ ├── hexbins.py │ ├── histogram_responsive.py │ ├── histogram_with_a_global_mean_overlay.py │ ├── horizon_graph.py │ ├── horizontal_stacked_bar_chart.py │ ├── image_tooltip.py │ ├── interactive_brush.py │ ├── interactive_cross_highlight.py │ ├── interactive_layered_crossfilter.py │ ├── interactive_legend.py │ ├── interactive_scatter_plot.py │ ├── interval_selection.py │ ├── iowa_electricity.py │ ├── isotype.py │ ├── isotype_emoji.py │ ├── isotype_grid.py │ ├── jitter_chart.py │ ├── layer_line_color_rule.py │ ├── layered_area_chart.py │ ├── layered_bar_chart.py │ ├── layered_chart_bar_mark.py │ ├── layered_chart_with_dual_axis.py │ ├── layered_heatmap_text.py │ ├── layered_histogram.py │ ├── line_chart_with_color_datum.py │ ├── line_chart_with_cumsum.py │ ├── line_chart_with_datum.py │ ├── line_chart_with_generator.py │ ├── line_chart_with_points.py │ ├── line_percent.py │ ├── line_with_ci.py │ ├── line_with_log_scale.py │ ├── london_tube.py │ ├── multi_series_line.py │ ├── multifeature_scatter_plot.py │ ├── multiline_highlight.py │ ├── multiline_tooltip.py │ ├── multiple_interactions.py │ ├── multiple_marks.py │ ├── natural_disasters.py │ ├── normalized_stacked_area_chart.py │ ├── normalized_stacked_bar_chart.py │ ├── normed_parallel_coordinates.py │ ├── one_dot_per_zipcode.py │ ├── pacman_chart.py │ ├── parallel_coordinates.py │ ├── percentage_of_total.py │ ├── pie_chart.py │ ├── pie_chart_with_labels.py │ ├── poly_fit_regression.py │ ├── pyramid.py │ ├── radial_chart.py │ ├── ranged_dot_plot.py │ ├── ridgeline_plot.py │ ├── scatter_href.py │ ├── scatter_linked_brush.py │ ├── scatter_linked_table.py │ ├── scatter_marginal_hist.py │ ├── scatter_matrix.py │ ├── scatter_qq.py │ ├── scatter_tooltips.py │ ├── scatter_with_histogram.py │ ├── scatter_with_labels.py │ ├── scatter_with_layered_histogram.py │ ├── scatter_with_loess.py │ ├── scatter_with_minimap.py │ ├── scatter_with_rolling_mean.py │ ├── seattle_weather_interactive.py │ ├── select_detail.py │ ├── select_mark_area.py │ ├── selection_histogram.py │ ├── selection_layer_bar_month.py │ ├── simple_bar_chart.py │ ├── simple_heatmap.py │ ├── simple_histogram.py │ ├── simple_line_chart.py │ ├── simple_scatter_with_errorbars.py │ ├── simple_stacked_area_chart.py │ ├── slider_cutoff.py │ ├── slope_graph.py │ ├── sorted_error_bars_with_ci.py │ ├── stacked_bar_chart.py │ ├── stacked_bar_chart_sorted_segments.py │ ├── stacked_bar_chart_with_text.py │ ├── stem_and_leaf.py │ ├── step_chart.py │ ├── streamgraph.py │ ├── strip_plot.py │ ├── stripplot.py │ ├── table_bubble_plot_github.py │ ├── tests │ │ ├── __init__.py │ │ └── test_examples.py │ ├── top_k_items.py │ ├── top_k_letters.py │ ├── top_k_with_others.py │ ├── trail_marker.py │ ├── trellis_area.py │ ├── trellis_area_sort_array.py │ ├── trellis_histogram.py │ ├── trellis_scatter_plot.py │ ├── trellis_stacked_bar_chart.py │ ├── us_employment.py │ ├── us_incomebrackets_by_state_facet.py │ ├── us_population_over_time.py │ ├── us_population_over_time_facet.py │ ├── us_population_pyramid_over_time.py │ ├── us_state_capitals.py │ ├── violin_plot.py │ ├── weather_heatmap.py │ ├── wheat_wages.py │ ├── wilkinson-dot-plot.py │ ├── wind_vector_map.py │ ├── window_rank.py │ ├── world_map.py │ └── world_projections.py ├── expr │ ├── __init__.py │ ├── consts.py │ ├── core.py │ ├── funcs.py │ └── tests │ │ ├── __init__.py │ │ └── test_expr.py ├── sphinxext │ ├── __init__.py │ ├── altairgallery.py │ ├── altairplot.py │ ├── schematable.py │ └── utils.py ├── tests │ ├── __init__.py │ └── test_magics.py ├── utils │ ├── __init__.py │ ├── core.py │ ├── data.py │ ├── deprecation.py │ ├── display.py │ ├── execeval.py │ ├── html.py │ ├── mimebundle.py │ ├── plugin_registry.py │ ├── save.py │ ├── schemapi.py │ ├── server.py │ ├── tests │ │ ├── __init__.py │ │ ├── test_core.py │ │ ├── test_data.py │ │ ├── test_deprecation.py │ │ ├── test_execeval.py │ │ ├── test_html.py │ │ ├── test_mimebundle.py │ │ ├── test_plugin_registry.py │ │ ├── test_schemapi.py │ │ ├── test_server.py │ │ └── test_utils.py │ └── theme.py ├── vega │ ├── __init__.py │ ├── data.py │ ├── display.py │ ├── tests │ │ ├── __init__.py │ │ └── test_import.py │ └── v5 │ │ ├── __init__.py │ │ ├── data.py │ │ ├── display.py │ │ └── schema │ │ ├── __init__.py │ │ ├── core.py │ │ └── vega-schema.json └── vegalite │ ├── __init__.py │ ├── api.py │ ├── data.py │ ├── display.py │ ├── schema.py │ ├── tests │ ├── __init__.py │ └── test_common.py │ ├── v3 │ ├── __init__.py │ ├── _deprecated.py │ ├── api.py │ ├── data.py │ ├── display.py │ ├── schema │ │ ├── __init__.py │ │ ├── channels.py │ │ ├── core.py │ │ ├── mixins.py │ │ └── vega-lite-schema.json │ ├── tests │ │ ├── __init__.py │ │ ├── test_api.py │ │ ├── test_data.py │ │ ├── test_display.py │ │ ├── test_geo_interface.py │ │ ├── test_renderers.py │ │ └── test_theme.py │ └── theme.py │ ├── v4 │ ├── __init__.py │ ├── api.py │ ├── data.py │ ├── display.py │ ├── schema │ │ ├── __init__.py │ │ ├── channels.py │ │ ├── core.py │ │ ├── mixins.py │ │ └── vega-lite-schema.json │ ├── tests │ │ ├── __init__.py │ │ ├── test_api.py │ │ ├── test_data.py │ │ ├── test_display.py │ │ ├── test_geo_interface.py │ │ ├── test_renderers.py │ │ └── test_theme.py │ └── theme.py │ └── v5 │ ├── __init__.py │ ├── api.py │ ├── data.py │ ├── display.py │ ├── schema │ ├── __init__.py │ ├── channels.py │ ├── core.py │ ├── mixins.py │ └── vega-lite-schema.json │ ├── tests │ ├── __init__.py │ ├── test_api.py │ ├── test_data.py │ ├── test_display.py │ ├── test_geo_interface.py │ ├── test_renderers.py │ └── test_theme.py │ └── theme.py ├── design ├── altair-logo-light.png ├── altair-logo-light.svg ├── altair-logo.png └── altair-logo.svg ├── doc ├── .gitignore ├── Makefile ├── _static │ ├── altair-gallery.css │ ├── altair-logo-light.png │ ├── altair-plot.css │ ├── chart.html │ ├── custom.css │ ├── favicon.ico │ ├── gray-square.png │ └── theme_overrides.css ├── _templates │ └── class.rst ├── case_studies │ └── exploring-weather.rst ├── conf.py ├── getting_started │ ├── installation.rst │ ├── overview.rst │ └── starting.rst ├── index.rst ├── make.bat ├── releases │ └── changes.rst ├── requirements.txt ├── sync_website.sh └── user_guide │ ├── API.rst │ ├── compound_charts.rst │ ├── configuration.rst │ ├── custom_renderers.rst │ ├── customization.rst │ ├── data.rst │ ├── data_transformers.rst │ ├── display_frontends.rst │ ├── ecosystem.rst │ ├── encoding.rst │ ├── faq.rst │ ├── importing.rst │ ├── interactions.rst │ ├── interactions2.rst │ ├── internals.rst │ ├── marks.rst │ ├── saving_charts.rst │ ├── scale_resolve.rst │ ├── times_and_dates.rst │ ├── transform │ ├── aggregate.rst │ ├── bin.rst │ ├── calculate.rst │ ├── density.rst │ ├── filter.rst │ ├── flatten.rst │ ├── fold.rst │ ├── impute.rst │ ├── index.rst │ ├── joinaggregate.rst │ ├── loess.rst │ ├── lookup.rst │ ├── pivot.rst │ ├── quantile.rst │ ├── regression.rst │ ├── sample.rst │ ├── stack.rst │ ├── timeunit.rst │ └── window.rst │ └── troubleshooting.rst ├── images ├── cars.png └── cars_scatter_bar.gif ├── paper ├── paper.bib ├── paper.md └── seattle_weather_interactive.png ├── pyproject.toml ├── requirements.txt ├── requirements_dev.txt ├── setup.cfg ├── setup.py └── tools ├── generate_api_docs.py ├── generate_schema_wrapper.py └── schemapi ├── __init__.py ├── codegen.py ├── decorator.py ├── jsonschema-draft04.json ├── schemapi.py ├── tests ├── __init__.py ├── test_decorator.py ├── test_schemapi.py └── test_utils.py └── utils.py /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Bug report' 3 | about: 'Create a bug report to help us improve' 4 | labels: 'bug' 5 | --- 6 | 7 | Type here... 8 | 9 | --- 10 | 11 | Please follow these steps to make it more efficient to solve your issue: 12 | 13 | - [ ] Since Altair is a Python wrapper around the Vega-Lite visualization grammar, [most bugs should be reported directly to Vega-Lite](https://github.com/vega/vega-lite/issues). You can click the Action Button of your Altair chart and "Open in Vega Editor" to create a reproducible Vega-Lite example and see if you get the same error in the Vega Editor. 14 | - [ ] Search for duplicate issues. 15 | - [ ] Use the latest version of Altair. 16 | - [ ] Describe how to reproduce the bug and include the full code and data to reproduce it, ideally using a sample data set from `vega_datasets`. 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Question 4 | url: https://stackoverflow.com/tags/altair 5 | about: Please ask questions such as "How do I do X?" or "Why does this not work?" on Stack Overflow using the `altair` tag. 6 | - name: Discussion 7 | url: https://github.com/altair-viz/altair/discussions 8 | about: If you want to discuss a topic or ask a question that is not a good fit for Stack Overflow, please open a new disscussion here on GitHub. 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Feature request' 3 | about: 'Suggest a new idea or feature' 4 | labels: 'enhancement' 5 | --- 6 | 7 | Type here... 8 | 9 | --- 10 | 11 | Please follow these steps to make it more efficient to respond to your feature request. 12 | 13 | - [ ] Since Altair is a Python wrapper around the Vega-Lite visualization grammar, [most feature requests should be reported directly to Vega-Lite](https://github.com/vega/vega-lite/issues). You can click the Action Button of your Altair chart and "Open in Vega Editor" to create a reproducible Vega-Lite example. 14 | - [ ] Search for duplicate issues. 15 | - [ ] Describe the feature's goal, motivating use cases, and its expected behavior. 16 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: [ '3.7', '3.8', '3.9', '3.10' ] 11 | name: Python ${{ matrix.python-version }} 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: Set up Python ${{ matrix.python-version }} 15 | uses: actions/setup-python@v1 16 | with: 17 | python-version: ${{ matrix.python-version }} 18 | - name: Set Up Chromedriver 19 | run: | 20 | sudo apt-get update 21 | sudo apt-get --only-upgrade install google-chrome-stable 22 | sudo apt-get -yqq install chromium-chromedriver 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install .[dev] 27 | pip install altair_saver 28 | pip install git+https://github.com/altair-viz/altair_viewer.git 29 | - name: Test with pytest 30 | run: | 31 | pytest --doctest-modules altair 32 | -------------------------------------------------------------------------------- /.github/workflows/docbuild.yml: -------------------------------------------------------------------------------- 1 | name: docbuild 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | build-type: [ 'html', 'doctest' ] 11 | name: ${{ matrix.build-type }} 12 | steps: 13 | - uses: actions/checkout@v1 14 | - name: Set up Python 3.10 15 | uses: actions/setup-python@v1 16 | with: 17 | python-version: "3.10" 18 | - name: Install dependencies 19 | run: | 20 | python -m pip install --upgrade pip 21 | pip install .[dev] 22 | pip install altair_saver 23 | pip install -r doc/requirements.txt 24 | pip install git+https://github.com/altair-viz/altair_viewer.git 25 | - name: Run docbuild 26 | run: | 27 | cd doc && make ${{ matrix.build-type }} 28 | 29 | 30 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | name: black-flake8 9 | steps: 10 | - uses: actions/checkout@v1 11 | - name: Set up Python 3.10 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: "3.10" 15 | - name: Check formatting with black 16 | run: | 17 | pip install black 18 | black --diff --color . 19 | black --check . 20 | - name: Lint with flake8 21 | run: | 22 | pip install flake8 23 | flake8 . --statistics 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # emacs backups 60 | *~ 61 | \#*\# 62 | 63 | .ipynb_checkpoints 64 | .idea/* 65 | tools/_build 66 | Untitled*.ipynb 67 | .mypy* 68 | .pytest_cache 69 | *.DS_Store 70 | 71 | # VSCode 72 | .vscode 73 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015-2022, Altair Developers 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of altair nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | include Makefile 3 | include LICENSE 4 | include CHANGES.md 5 | include requirements.txt 6 | include requirements_dev.txt 7 | recursive-include altair *.py *.json *.ipynb *.html 8 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: install 2 | 3 | install: 4 | python setup.py install 5 | 6 | test : 7 | black . 8 | flake8 . --statistics 9 | python -m pytest --pyargs --doctest-modules altair 10 | 11 | test-coverage: 12 | python -m pytest --pyargs --doctest-modules --cov=altair --cov-report term altair 13 | 14 | test-coverage-html: 15 | python -m pytest --pyargs --doctest-modules --cov=altair --cov-report html altair 16 | -------------------------------------------------------------------------------- /altair/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | __version__ = "4.3.0.dev0" 3 | 4 | from .vegalite import * 5 | from . import examples 6 | 7 | 8 | def load_ipython_extension(ipython): 9 | from ._magics import vega, vegalite 10 | 11 | ipython.register_magic_function(vega, "cell") 12 | ipython.register_magic_function(vegalite, "cell") 13 | -------------------------------------------------------------------------------- /altair/datasets.py: -------------------------------------------------------------------------------- 1 | """Datasets for use with Altair (deprecated) 2 | 3 | The functions here are merely thin wrappers for data access routines in the 4 | vega_datasets package. 5 | """ 6 | from altair.utils.deprecation import deprecated 7 | 8 | 9 | @deprecated("load_dataset is deprecated. " "Use the vega_datasets package instead.") 10 | def load_dataset(name): 11 | """Load a dataset by name as a pandas.DataFrame.""" 12 | import vega_datasets 13 | 14 | return vega_datasets.data(name) 15 | 16 | 17 | @deprecated("load_dataset is deprecated. " "Use the vega_datasets package instead.") 18 | def list_datasets(): 19 | """List the available datasets.""" 20 | import vega_datasets 21 | 22 | return vega_datasets.data.list_datasets() 23 | -------------------------------------------------------------------------------- /altair/examples/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def iter_examples(): 5 | """Iterate over the examples in this directory. 6 | 7 | Each item is a dict with the following keys: 8 | - "name" : the unique name of the example 9 | - "filename" : the full file path to the example 10 | """ 11 | example_dir = os.path.abspath(os.path.dirname(__file__)) 12 | for filename in os.listdir(example_dir): 13 | name, ext = os.path.splitext(filename) 14 | if name.startswith('_') or ext != '.py': 15 | continue 16 | yield {'name': name, 17 | 'filename': os.path.join(example_dir, filename)} 18 | -------------------------------------------------------------------------------- /altair/examples/airports.py: -------------------------------------------------------------------------------- 1 | """ 2 | Locations of US Airports 3 | ======================== 4 | This is a layered geographic visualization that shows the positions of US 5 | airports on a background of US states. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | airports = data.airports() 12 | states = alt.topo_feature(data.us_10m.url, feature='states') 13 | 14 | # US states background 15 | background = alt.Chart(states).mark_geoshape( 16 | fill='lightgray', 17 | stroke='white' 18 | ).properties( 19 | width=500, 20 | height=300 21 | ).project('albersUsa') 22 | 23 | # airport positions on background 24 | points = alt.Chart(airports).mark_circle( 25 | size=10, 26 | color='steelblue' 27 | ).encode( 28 | longitude='longitude:Q', 29 | latitude='latitude:Q', 30 | tooltip=['name', 'city', 'state'] 31 | ) 32 | 33 | background + points 34 | -------------------------------------------------------------------------------- /altair/examples/airports_count.py: -------------------------------------------------------------------------------- 1 | """ 2 | Locations of US Airports 3 | ======================== 4 | This is a layered geographic visualization that shows the positions of US 5 | airports on a background of US states. 6 | """ 7 | # category: maps 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | airports = data.airports.url 12 | states = alt.topo_feature(data.us_10m.url, feature='states') 13 | 14 | # US states background 15 | background = alt.Chart(states).mark_geoshape( 16 | fill='lightgray', 17 | stroke='white' 18 | ).properties( 19 | width=500, 20 | height=300 21 | ).project('albersUsa') 22 | 23 | # airport positions on background 24 | points = alt.Chart(airports).transform_aggregate( 25 | latitude='mean(latitude)', 26 | longitude='mean(longitude)', 27 | count='count()', 28 | groupby=['state'] 29 | ).mark_circle().encode( 30 | longitude='longitude:Q', 31 | latitude='latitude:Q', 32 | size=alt.Size('count:Q', title='Number of Airports'), 33 | color=alt.value('steelblue'), 34 | tooltip=['state:N','count:Q'] 35 | ).properties( 36 | title='Number of airports in US' 37 | ) 38 | 39 | background + points 40 | -------------------------------------------------------------------------------- /altair/examples/anscombe_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Anscombe's Quartet 3 | ------------------ 4 | 5 | This example shows how to use the column channel to make a trellis plot. Anscombe's Quartet is a famous dataset constructed by Francis Anscombe. Common summary statistics are identical for each subset of the data, despite the subsets having vastly different characteristics. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.anscombe() 12 | 13 | alt.Chart(source).mark_circle().encode( 14 | alt.X('X', scale=alt.Scale(zero=False)), 15 | alt.Y('Y', scale=alt.Scale(zero=False)), 16 | alt.Facet('Series', columns=2), 17 | ).properties( 18 | width=180, 19 | height=180, 20 | ) 21 | -------------------------------------------------------------------------------- /altair/examples/area_chart_gradient.py: -------------------------------------------------------------------------------- 1 | """ 2 | Area Chart with Gradient 3 | ------------------------ 4 | This example shows how to make an area chart with a gradient fill. 5 | For more information about gradient options see the Vega-Lite `Gradient documentation `_. 6 | """ 7 | # category: area charts 8 | 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.stocks() 13 | 14 | alt.Chart(source).transform_filter( 15 | 'datum.symbol==="GOOG"' 16 | ).mark_area( 17 | line={'color':'darkgreen'}, 18 | color=alt.Gradient( 19 | gradient='linear', 20 | stops=[alt.GradientStop(color='white', offset=0), 21 | alt.GradientStop(color='darkgreen', offset=1)], 22 | x1=1, 23 | x2=1, 24 | y1=1, 25 | y2=0 26 | ) 27 | ).encode( 28 | alt.X('date:T'), 29 | alt.Y('price:Q') 30 | ) -------------------------------------------------------------------------------- /altair/examples/bar_and_line_with_dual_axis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Line on Dual Axis 3 | -------------------------------- 4 | This example shows how to combine two plots and keep their axes. 5 | 6 | For a more polished version of this chart, see :ref:`gallery_wheat_wages`. 7 | """ 8 | # category: bar charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.wheat() 13 | 14 | base = alt.Chart(source).encode(x='year:O') 15 | 16 | bar = base.mark_bar().encode(y='wheat:Q') 17 | 18 | line = base.mark_line(color='red').encode( 19 | y='wages:Q' 20 | ) 21 | 22 | (bar + line).properties(width=600) 23 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_horizontal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Horizontal Bar Chart 3 | -------------------- 4 | This example is a bar chart drawn horizontally by putting the quantitative value on the x axis. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='wheat:Q', 14 | y="year:O" 15 | ).properties(height=700) 16 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_sorted.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sorted Bar Chart 3 | ================ 4 | This example shows a bar chart sorted by a calculated value. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='sum(yield):Q', 14 | y=alt.Y('site:N', sort='-x') 15 | ) 16 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_with_highlighted_bar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Highlighted Bar 3 | ------------------------------ 4 | This example shows a basic bar chart with a single bar highlighted. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='year:O', 14 | y="wheat:Q", 15 | # The highlight will be set on the result of a conditional statement 16 | color=alt.condition( 17 | alt.datum.year == 1810, # If the year is 1810 this test returns True, 18 | alt.value('orange'), # which sets the bar orange. 19 | alt.value('steelblue') # And if it's not true it sets the bar steelblue. 20 | ) 21 | ).properties(width=600) 22 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_with_highlighted_segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Highlighted Segment 3 | ---------------------------------- 4 | This example shows a bar chart that highlights values beyond a threshold. 5 | """ 6 | import altair as alt 7 | import pandas as pd 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | threshold = pd.DataFrame([{"threshold": 90}]) 12 | 13 | bars = alt.Chart(source).mark_bar().encode( 14 | x="year:O", 15 | y="wheat:Q", 16 | ) 17 | 18 | highlight = alt.Chart(source).mark_bar(color="#e45755").encode( 19 | x='year:O', 20 | y='baseline:Q', 21 | y2='wheat:Q' 22 | ).transform_filter( 23 | alt.datum.wheat > 90 24 | ).transform_calculate("baseline", "90") 25 | 26 | rule = alt.Chart(threshold).mark_rule().encode( 27 | y='threshold:Q' 28 | ) 29 | 30 | (bars + highlight + rule).properties(width=600) 31 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_with_labels.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Labels 3 | ===================== 4 | This example shows a basic horizontal bar chart with labels created with Altair. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | bars = alt.Chart(source).mark_bar().encode( 13 | x='wheat:Q', 14 | y="year:O" 15 | ) 16 | 17 | text = bars.mark_text( 18 | align='left', 19 | baseline='middle', 20 | dx=3 # Nudges text to right so it doesn't appear on top of the bar 21 | ).encode( 22 | text='wheat:Q' 23 | ) 24 | 25 | (bars + text).properties(height=900) 26 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_with_mean_line.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Line at Mean 3 | --------------------------- 4 | This example shows the mean value overlayed on a bar chart. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | bar = alt.Chart(source).mark_bar().encode( 13 | x='year:O', 14 | y='wheat:Q' 15 | ) 16 | 17 | rule = alt.Chart(source).mark_rule(color='red').encode( 18 | y='mean(wheat):Q' 19 | ) 20 | 21 | (bar + rule).properties(width=600) 22 | -------------------------------------------------------------------------------- /altair/examples/bar_chart_with_negatives.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Negative Values 3 | ============================== 4 | This example shows a bar chart with both positive and negative values. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.us_employment() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x="month:T", 14 | y="nonfarm_change:Q", 15 | color=alt.condition( 16 | alt.datum.nonfarm_change > 0, 17 | alt.value("steelblue"), # The positive color 18 | alt.value("orange") # The negative color 19 | ) 20 | ).properties(width=600) 21 | -------------------------------------------------------------------------------- /altair/examples/bar_rounded.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with rounded edges 3 | ---------------------------- 4 | This example shows how to create a bar chart with rounded edges. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.seattle_weather() 11 | 12 | alt.Chart(source).mark_bar( 13 | cornerRadiusTopLeft=3, 14 | cornerRadiusTopRight=3 15 | ).encode( 16 | x='month(date):O', 17 | y='count():Q', 18 | color='weather:N' 19 | ) 20 | -------------------------------------------------------------------------------- /altair/examples/bar_with_rolling_mean.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar Chart with Rolling Mean 3 | --------------------------- 4 | A bar chart overlayed with a rolling mean. In this example the average of values over the previous decade is displayed as a line. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | bar = alt.Chart(source).mark_bar().encode( 13 | x='year:O', 14 | y='wheat:Q' 15 | ) 16 | 17 | line = alt.Chart(source).mark_line(color='red').transform_window( 18 | # The field to average 19 | rolling_mean='mean(wheat)', 20 | # The number of values before and after the current value to include. 21 | frame=[-9, 0] 22 | ).encode( 23 | x='year:O', 24 | y='rolling_mean:Q' 25 | ) 26 | 27 | (bar + line).properties(width=600) 28 | -------------------------------------------------------------------------------- /altair/examples/beckers_barley_trellis_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Becker's Barley Trellis Plot 3 | ---------------------------- 4 | The example demonstrates the trellis charts created by Richard Becker, William Cleveland and others in the 1990s. Using the visualization technique below they identified an anomoly in a widely used agriculatural dataset, which they termed `"The Morris Mistake." `_. It became their favored way of showcasing the power of this pioneering plot. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source, title="The Morris Mistake").mark_point().encode( 13 | alt.X( 14 | 'yield:Q', 15 | title="Barley Yield (bushels/acre)", 16 | scale=alt.Scale(zero=False), 17 | axis=alt.Axis(grid=False) 18 | ), 19 | alt.Y( 20 | 'variety:N', 21 | title="", 22 | sort='-x', 23 | axis=alt.Axis(grid=True) 24 | ), 25 | color=alt.Color('year:N', legend=alt.Legend(title="Year")), 26 | row=alt.Row( 27 | 'site:N', 28 | title="", 29 | sort=alt.EncodingSortField(field='yield', op='sum', order='descending'), 30 | ) 31 | ).properties( 32 | height=alt.Step(20) 33 | ).configure_view(stroke="transparent") 34 | -------------------------------------------------------------------------------- /altair/examples/beckers_barley_wrapped_facet.py: -------------------------------------------------------------------------------- 1 | """ 2 | Becker's Barley Trellis Plot (wrapped facet) 3 | -------------------------------------------- 4 | The example demonstrates the trellis charts created by Richard Becker, William Cleveland and others in the 1990s. 5 | This is the Altair replicate of `the VegaLite version `_ 6 | demonstrating the usage of `columns` argument to create wrapped facet. 7 | """ 8 | # category: other charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.barley.url 13 | 14 | alt.Chart(source).mark_point().encode( 15 | alt.X('median(yield):Q', scale=alt.Scale(zero=False)), 16 | y='variety:O', 17 | color='year:N', 18 | facet=alt.Facet('site:O', columns=2), 19 | ).properties( 20 | width=200, 21 | height=100, 22 | ) 23 | -------------------------------------------------------------------------------- /altair/examples/binned_heatmap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Binned Heatmap 3 | -------------- 4 | This example shows how to make a heatmap from binned quantitative data. 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.movies.url 11 | 12 | alt.Chart(source).mark_rect().encode( 13 | alt.X('IMDB_Rating:Q', bin=alt.Bin(maxbins=60)), 14 | alt.Y('Rotten_Tomatoes_Rating:Q', bin=alt.Bin(maxbins=40)), 15 | alt.Color('count():Q', scale=alt.Scale(scheme='greenblue')) 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/binned_scatterplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Binned Scatterplot 3 | ------------------ 4 | This example shows how to make a binned scatterplot. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.movies.url 11 | 12 | alt.Chart(source).mark_circle().encode( 13 | alt.X('IMDB_Rating:Q', bin=True), 14 | alt.Y('Rotten_Tomatoes_Rating:Q', bin=True), 15 | size='count()' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/boxplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Boxplot with Min/Max Whiskers 3 | ------------------------------ 4 | This example shows how to make a boxplot using US Population data from 2000. 5 | Note that the default value of the `extent` property is 1.5, 6 | which represents the convention of extending the whiskers 7 | to the furthest points within 1.5 * IQR from the first and third quartile. 8 | """ 9 | # category: other charts 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.population.url 14 | 15 | alt.Chart(source).mark_boxplot(extent='min-max').encode( 16 | x='age:O', 17 | y='people:Q' 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/bubble_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bubble Plot 3 | ----------------- 4 | This example shows how to make a bubble plot. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.cars() 11 | 12 | alt.Chart(source).mark_point().encode( 13 | x='Horsepower', 14 | y='Miles_per_Gallon', 15 | size='Acceleration' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/bump_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bump Chart 3 | ---------- 4 | This example shows a bump chart. The data is first grouped into six-month 5 | intervals using pandas. The ranks are computed by Altair using a 6 | window transform. 7 | """ 8 | # category: line charts 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | import pandas as pd 13 | 14 | stocks = data.stocks() 15 | source = stocks.groupby([pd.Grouper(key="date", freq="6M"),"symbol"]).mean().reset_index() 16 | 17 | alt.Chart(source).mark_line(point = True).encode( 18 | x = alt.X("date:O", timeUnit="yearmonth", title="date"), 19 | y="rank:O", 20 | color=alt.Color("symbol:N") 21 | ).transform_window( 22 | rank="rank()", 23 | sort=[alt.SortField("price", order="descending")], 24 | groupby=["date"] 25 | ).properties( 26 | title="Bump Chart for Stock Prices", 27 | width=600, 28 | height=150, 29 | ) -------------------------------------------------------------------------------- /altair/examples/candlestick_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Candlestick Chart 3 | ================= 4 | A candlestick chart inspired from `Protovis `_. 5 | This example shows the performance of the Chicago Board Options Exchange `Volatility Index `_ (VIX) 6 | in the summer of 2009. The thick bar represents the opening and closing prices, 7 | while the thin bar shows intraday high and low prices; if the index closed higher on a given day, the bars are colored green rather than red. 8 | """ 9 | # category: other charts 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.ohlc() 14 | 15 | open_close_color = alt.condition("datum.open <= datum.close", 16 | alt.value("#06982d"), 17 | alt.value("#ae1325")) 18 | 19 | base = alt.Chart(source).encode( 20 | alt.X('date:T', 21 | axis=alt.Axis( 22 | format='%m/%d', 23 | labelAngle=-45, 24 | title='Date in 2009' 25 | ) 26 | ), 27 | color=open_close_color 28 | ) 29 | 30 | rule = base.mark_rule().encode( 31 | alt.Y( 32 | 'low:Q', 33 | title='Price', 34 | scale=alt.Scale(zero=False), 35 | ), 36 | alt.Y2('high:Q') 37 | ) 38 | 39 | bar = base.mark_bar().encode( 40 | alt.Y('open:Q'), 41 | alt.Y2('close:Q') 42 | ) 43 | 44 | rule + bar -------------------------------------------------------------------------------- /altair/examples/choropleth.py: -------------------------------------------------------------------------------- 1 | """ 2 | Choropleth Map 3 | ============== 4 | A choropleth map of unemployment rate per county in the US 5 | """ 6 | # category: maps 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | counties = alt.topo_feature(data.us_10m.url, 'counties') 11 | source = data.unemployment.url 12 | 13 | alt.Chart(counties).mark_geoshape().encode( 14 | color='rate:Q' 15 | ).transform_lookup( 16 | lookup='id', 17 | from_=alt.LookupData(source, 'id', ['rate']) 18 | ).project( 19 | type='albersUsa' 20 | ).properties( 21 | width=500, 22 | height=300 23 | ) 24 | -------------------------------------------------------------------------------- /altair/examples/choropleth_repeat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Repeated Choropleth Map 3 | ======================= 4 | Three choropleths representing disjoint data from the same table. 5 | """ 6 | # category: maps 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | states = alt.topo_feature(data.us_10m.url, 'states') 11 | source = data.population_engineers_hurricanes.url 12 | variable_list = ['population', 'engineers', 'hurricanes'] 13 | 14 | alt.Chart(states).mark_geoshape().encode( 15 | alt.Color(alt.repeat('row'), type='quantitative') 16 | ).transform_lookup( 17 | lookup='id', 18 | from_=alt.LookupData(source, 'id', variable_list) 19 | ).properties( 20 | width=500, 21 | height=300 22 | ).project( 23 | type='albersUsa' 24 | ).repeat( 25 | row=variable_list 26 | ).resolve_scale( 27 | color='independent' 28 | ) 29 | -------------------------------------------------------------------------------- /altair/examples/co2_concentration.py: -------------------------------------------------------------------------------- 1 | """ 2 | Atmospheric CO2 Concentration 3 | ----------------------------- 4 | This example is a fully developed line chart that uses a window transformation. 5 | It was inspired by `Gregor Aisch's work at datawrapper 6 | `_. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.co2_concentration.url 13 | 14 | base = alt.Chart( 15 | source, 16 | title="Carbon Dioxide in the Atmosphere" 17 | ).transform_calculate( 18 | year="year(datum.Date)" 19 | ).transform_calculate( 20 | decade="floor(datum.year / 10)" 21 | ).transform_calculate( 22 | scaled_date="(datum.year % 10) + (month(datum.Date)/12)" 23 | ).transform_window( 24 | first_date='first_value(scaled_date)', 25 | last_date='last_value(scaled_date)', 26 | sort=[{"field": "scaled_date", "order": "ascending"}], 27 | groupby=['decade'], 28 | frame=[None, None] 29 | ).transform_calculate( 30 | end="datum.first_date === datum.scaled_date ? 'first' : datum.last_date === datum.scaled_date ? 'last' : null" 31 | ).encode( 32 | x=alt.X( 33 | "scaled_date:Q", 34 | axis=alt.Axis(title="Year into Decade", tickCount=11) 35 | ), 36 | y=alt.Y( 37 | "CO2:Q", 38 | title="CO2 concentration in ppm", 39 | scale=alt.Scale(zero=False) 40 | ) 41 | ) 42 | 43 | line = base.mark_line().encode( 44 | color=alt.Color( 45 | "decade:O", 46 | scale=alt.Scale(scheme="magma"), 47 | legend=None 48 | ) 49 | ) 50 | 51 | text = base.encode(text="year:N") 52 | 53 | start_year = text.transform_filter( 54 | alt.datum.end == 'first' 55 | ).mark_text(baseline="top") 56 | 57 | end_year = text.transform_filter( 58 | alt.datum.end == 'last' 59 | ).mark_text(baseline="bottom") 60 | 61 | (line + start_year + end_year).configure_text( 62 | align="left", 63 | dx=1, 64 | dy=3 65 | ).properties(width=600, height=375) 66 | -------------------------------------------------------------------------------- /altair/examples/comet_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Comet Chart Example 3 | ---------------------------- 4 | Inspired by `Zan Armstrong's comet chart `_ 5 | this plot uses ``mark_trail`` to visualize change of grouped data over time. 6 | A more elaborate example and explanation of creating comet charts in Altair 7 | is shown in `this blogpost `_. 8 | """ 9 | # category: other charts 10 | 11 | import altair as alt 12 | import vega_datasets 13 | 14 | ( 15 | alt.Chart(vega_datasets.data.barley.url) 16 | .transform_pivot("year", value="yield", groupby=["variety", "site"]) 17 | .transform_fold(["1931", "1932"], as_=["year", "yield"]) 18 | .transform_calculate(calculate="datum['1932'] - datum['1931']", as_="delta") 19 | .mark_trail() 20 | .encode( 21 | x=alt.X('year:O', title=None), 22 | y=alt.Y('variety:N', title='Variety'), 23 | size=alt.Size('yield:Q', scale=alt.Scale(range=[0, 12]), legend=alt.Legend(values=[20, 60], title='Barley Yield (bushels/acre)')), 24 | color=alt.Color('delta:Q', scale=alt.Scale(domainMid=0), legend=alt.Legend(title='Yield Delta (%)')), 25 | tooltip=alt.Tooltip(['year:O', 'yield:Q']), 26 | column=alt.Column('site:N', title='Site') 27 | 28 | ) 29 | .configure_view(stroke=None) 30 | .configure_legend(orient='bottom', direction='horizontal') 31 | .properties(title='Barley Yield comparison between 1932 and 1931') 32 | ) 33 | -------------------------------------------------------------------------------- /altair/examples/connected_scatterplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Connected Scatterplot (Lines with Custom Paths) 3 | ----------------------------------------------- 4 | 5 | This example show how the order encoding can be used to draw a custom path. The dataset tracks miles driven per capita along with gas prices annually from 1956 to 2010. 6 | It is based on Hannah Fairfield's article 'Driving Shifts Into Reverse'. See https://archive.nytimes.com/www.nytimes.com/imagepages/2010/05/02/business/02metrics.html for the original. 7 | """ 8 | # category: scatter plots 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.driving() 13 | 14 | alt.Chart(source).mark_line(point=True).encode( 15 | alt.X('miles', scale=alt.Scale(zero=False)), 16 | alt.Y('gas', scale=alt.Scale(zero=False)), 17 | order='year' 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/cumulative_count_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cumulative Count Chart 3 | ---------------------- 4 | This example shows an area chart with cumulative count. 5 | Adapted from https://vega.github.io/vega-lite/examples/area_cumulative_freq.html 6 | 7 | """ 8 | # category: area charts 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.movies.url 14 | 15 | alt.Chart(source).transform_window( 16 | cumulative_count="count()", 17 | sort=[{"field": "IMDB_Rating"}], 18 | ).mark_area().encode( 19 | x="IMDB_Rating:Q", 20 | y="cumulative_count:Q" 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/cumulative_wiki_donations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cumulative Wikipedia Donations 3 | ============================== 4 | 5 | This chart shows cumulative donations to Wikipedia over the past 10 years. Inspired by this `Reddit post `_ but using lines instead of areas. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | 10 | source = "https://frdata.wikimedia.org/donationdata-vs-day.csv" 11 | 12 | alt.Chart(source).mark_line().encode( 13 | alt.X('monthdate(date):T', title='Month', axis=alt.Axis(format='%B')), 14 | alt.Y('max(ytdsum):Q', title='Cumulative Donations', stack=None), 15 | alt.Color('year(date):O', legend=alt.Legend(title='Year')), 16 | alt.Order('year(data):O') 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/density_facet.py: -------------------------------------------------------------------------------- 1 | """ 2 | Faceted Density Estimates 3 | ------------------------- 4 | Density estimates of measurements for each iris flower feature 5 | """ 6 | # category: area charts 7 | 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.iris() 12 | 13 | alt.Chart(source).transform_fold( 14 | ['petalWidth', 15 | 'petalLength', 16 | 'sepalWidth', 17 | 'sepalLength'], 18 | as_ = ['Measurement_type', 'value'] 19 | ).transform_density( 20 | density='value', 21 | bandwidth=0.3, 22 | groupby=['Measurement_type'], 23 | extent= [0, 8] 24 | ).mark_area().encode( 25 | alt.X('value:Q'), 26 | alt.Y('density:Q'), 27 | alt.Row('Measurement_type:N') 28 | ).properties(width=300, height=50) 29 | -------------------------------------------------------------------------------- /altair/examples/density_stack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stacked Density Estimates 3 | ------------------------- 4 | To plot a stacked graph of estimates, use a shared ``extent`` and a fixed 5 | number of subdivision ``steps`` to ensure that the points for each area align 6 | well. Density estimates of measurements for each iris flower feature are plot 7 | in a stacked method. In addition, setting ``counts`` to true multiplies the 8 | densities by the number of data points in each group, preserving proportional 9 | differences. 10 | """ 11 | # category: area charts 12 | 13 | import altair as alt 14 | from vega_datasets import data 15 | 16 | source = data.iris() 17 | 18 | alt.Chart(source).transform_fold( 19 | ['petalWidth', 20 | 'petalLength', 21 | 'sepalWidth', 22 | 'sepalLength'], 23 | as_ = ['Measurement_type', 'value'] 24 | ).transform_density( 25 | density='value', 26 | bandwidth=0.3, 27 | groupby=['Measurement_type'], 28 | extent= [0, 8], 29 | counts = True, 30 | steps=200 31 | ).mark_area().encode( 32 | alt.X('value:Q'), 33 | alt.Y('density:Q', stack='zero'), 34 | alt.Color('Measurement_type:N') 35 | ).properties(width=400, height=100) 36 | -------------------------------------------------------------------------------- /altair/examples/donut_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Donut Chart 3 | ----------- 4 | This example shows how to make a Donut Chart using ``mark_arc``. 5 | This is adapted from a corresponding Vega-Lite Example: 6 | `Donut Chart `_. 7 | """ 8 | # category: circular plots 9 | 10 | import pandas as pd 11 | import altair as alt 12 | 13 | source = pd.DataFrame({"category": [1, 2, 3, 4, 5, 6], "value": [4, 6, 10, 3, 7, 8]}) 14 | 15 | alt.Chart(source).mark_arc(innerRadius=50).encode( 16 | theta=alt.Theta(field="value", type="quantitative"), 17 | color=alt.Color(field="category", type="nominal"), 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/dot_dash_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dot Dash Plot 3 | ============= 4 | How to make the dot-dash plot presented in Edward Tufte's `Visual Display of Quantitative Information `_. Based 5 | on a JavaScript implementation by `g3o2 `_. 6 | """ 7 | # category: scatter plots 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | # Configure the options common to all layers 14 | brush = alt.selection(type='interval') 15 | base = alt.Chart(source).add_selection(brush) 16 | 17 | # Configure the points 18 | points = base.mark_point().encode( 19 | x=alt.X('Miles_per_Gallon', title=''), 20 | y=alt.Y('Horsepower', title=''), 21 | color=alt.condition(brush, 'Origin', alt.value('grey')) 22 | ) 23 | 24 | # Configure the ticks 25 | tick_axis = alt.Axis(labels=False, domain=False, ticks=False) 26 | 27 | x_ticks = base.mark_tick().encode( 28 | alt.X('Miles_per_Gallon', axis=tick_axis), 29 | alt.Y('Origin', title='', axis=tick_axis), 30 | color=alt.condition(brush, 'Origin', alt.value('lightgrey')) 31 | ) 32 | 33 | y_ticks = base.mark_tick().encode( 34 | alt.X('Origin', title='', axis=tick_axis), 35 | alt.Y('Horsepower', axis=tick_axis), 36 | color=alt.condition(brush, 'Origin', alt.value('lightgrey')) 37 | ) 38 | 39 | # Build the chart 40 | y_ticks | (points & x_ticks) 41 | -------------------------------------------------------------------------------- /altair/examples/errorbars_with_ci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Error Bars showing Confidence Interval 3 | ====================================== 4 | This example shows how to show error bars using confidence intervals. 5 | The confidence intervals are computed internally in vega by a non-parametric 6 | `bootstrap of the mean `_. 7 | """ 8 | # category: other charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.barley() 13 | 14 | error_bars = alt.Chart(source).mark_errorbar(extent='ci').encode( 15 | x=alt.X('yield:Q', scale=alt.Scale(zero=False)), 16 | y=alt.Y('variety:N') 17 | ) 18 | 19 | points = alt.Chart(source).mark_point(filled=True, color='black').encode( 20 | x=alt.X('yield:Q', aggregate='mean'), 21 | y=alt.Y('variety:N'), 22 | ) 23 | 24 | error_bars + points 25 | -------------------------------------------------------------------------------- /altair/examples/errorbars_with_std.py: -------------------------------------------------------------------------------- 1 | """ 2 | Error Bar with Standard Deviation 3 | --------------------------------- 4 | This example shows how to show error bars with standard deviation using crop yields data of different 5 | in the years of 1930s. 6 | """ 7 | # category: other charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.barley() 12 | 13 | error_bars = alt.Chart(source).mark_errorbar(extent='stdev').encode( 14 | x=alt.X('yield:Q', scale=alt.Scale(zero=False)), 15 | y=alt.Y('variety:N') 16 | ) 17 | 18 | points = alt.Chart(source).mark_point(filled=True, color='black').encode( 19 | x=alt.X('yield:Q', aggregate='mean'), 20 | y=alt.Y('variety:N'), 21 | ) 22 | 23 | error_bars + points 24 | -------------------------------------------------------------------------------- /altair/examples/filled_step_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Filled Step Chart 3 | ----------------- 4 | This example shows Google's stock price over time as a step chart with its area filled in and its line emphasized. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.stocks() 11 | 12 | alt.Chart(source).mark_area( 13 | color="lightblue", 14 | interpolate='step-after', 15 | line=True 16 | ).encode( 17 | x='date', 18 | y='price' 19 | ).transform_filter(alt.datum.symbol == 'GOOG') 20 | -------------------------------------------------------------------------------- /altair/examples/gantt_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Gantt Chart 3 | ----------------- 4 | This example shows how to make a simple Gantt chart. 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | import pandas as pd 9 | 10 | source = pd.DataFrame([ 11 | {"task": "A", "start": 1, "end": 3}, 12 | {"task": "B", "start": 3, "end": 8}, 13 | {"task": "C", "start": 8, "end": 10} 14 | ]) 15 | 16 | alt.Chart(source).mark_bar().encode( 17 | x='start', 18 | x2='end', 19 | y='task' 20 | ) 21 | -------------------------------------------------------------------------------- /altair/examples/gapminder_bubble_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Gapminder Bubble Plot 3 | ===================== 4 | This example shows how to make a bubble plot showing the correlation between 5 | health and income for 187 countries in the world (modified from an example 6 | in Lisa Charlotte Rost's blog post `'One Chart, Twelve Charting Libraries' `_. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.gapminder_health_income.url 13 | 14 | alt.Chart(source).mark_circle().encode( 15 | alt.X('income:Q', scale=alt.Scale(type='log')), 16 | alt.Y('health:Q', scale=alt.Scale(zero=False)), 17 | size='population:Q' 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/grouped_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grouped Bar Chart 3 | ----------------- 4 | This example shows a grouped bar chart. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='year:O', 14 | y='sum(yield):Q', 15 | color='year:N', 16 | column='site:N' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/grouped_bar_chart2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grouped Bar Chart with xOffset 3 | ------------------------------ 4 | Like :ref:`gallery_grouped_bar_chart`, this example shows a grouped bar chart. Whereas :ref:`gallery_grouped_bar_chart` used the ``column`` encoding channel, this example uses the ``xOffset`` encoding channel. This is adapted from a corresponding Vega-Lite Example: 5 | `Grouped Bar Chart `_. 6 | """ 7 | # category: bar charts 8 | import altair as alt 9 | import pandas as pd 10 | 11 | source = pd.DataFrame({"Category":list("AAABBBCCC"), 12 | "Group":list("xyzxyzxyz"), 13 | "Value":[0.1, 0.6, 0.9, 0.7, 0.2, 1.1, 0.6, 0.1, 0.2]}) 14 | 15 | alt.Chart(source).mark_bar().encode( 16 | x="Category:N", 17 | y="Value:Q", 18 | xOffset="Group:N", 19 | color="Group:N" 20 | ) 21 | -------------------------------------------------------------------------------- /altair/examples/grouped_bar_chart_horizontal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Horizontal Grouped Bar Chart 3 | ---------------------------- 4 | This example shows a horizontal grouped bar chart. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='sum(yield):Q', 14 | y='year:O', 15 | color='year:N', 16 | row='site:N' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/grouped_bar_chart_with_error_bars.py: -------------------------------------------------------------------------------- 1 | """ 2 | Grouped Bar Chart with Error Bars 3 | --------------------------------- 4 | This example shows a grouped bar chart with error bars. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | bars = alt.Chart().mark_bar().encode( 13 | x='year:O', 14 | y=alt.Y('mean(yield):Q', title='Mean Yield'), 15 | color='year:N', 16 | ) 17 | 18 | error_bars = alt.Chart().mark_errorbar(extent='ci').encode( 19 | x='year:O', 20 | y='yield:Q' 21 | ) 22 | 23 | alt.layer(bars, error_bars, data=source).facet( 24 | column='site:N' 25 | ) 26 | -------------------------------------------------------------------------------- /altair/examples/hexbins.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hexbin Chart 3 | ----------------- 4 | This example shows a hexbin chart. 5 | """ 6 | import altair as alt 7 | from vega_datasets import data 8 | 9 | source = data.seattle_weather() 10 | 11 | # Size of the hexbins 12 | size = 15 13 | # Count of distinct x features 14 | xFeaturesCount = 12 15 | # Count of distinct y features 16 | yFeaturesCount = 7 17 | # Name of the x field 18 | xField = 'date' 19 | # Name of the y field 20 | yField = 'date' 21 | 22 | # the shape of a hexagon 23 | hexagon = "M0,-2.3094010768L2,-1.1547005384 2,1.1547005384 0,2.3094010768 -2,1.1547005384 -2,-1.1547005384Z" 24 | 25 | alt.Chart(source).mark_point(size=size**2, shape=hexagon).encode( 26 | x=alt.X('xFeaturePos:Q', axis=alt.Axis(title='Month', 27 | grid=False, tickOpacity=0, domainOpacity=0)), 28 | y=alt.Y('day(' + yField + '):O', axis=alt.Axis(title='Weekday', 29 | labelPadding=20, tickOpacity=0, domainOpacity=0)), 30 | stroke=alt.value('black'), 31 | strokeWidth=alt.value(0.2), 32 | fill=alt.Color('mean(temp_max):Q', scale=alt.Scale(scheme='darkblue')), 33 | tooltip=['month(' + xField + '):O', 'day(' + yField + '):O', 'mean(temp_max):Q'] 34 | ).transform_calculate( 35 | # This field is required for the hexagonal X-Offset 36 | xFeaturePos='(day(datum.' + yField + ') % 2) / 2 + month(datum.' + xField + ')' 37 | ).properties( 38 | # Exact scaling factors to make the hexbins fit 39 | width=size * xFeaturesCount * 2, 40 | height=size * yFeaturesCount * 1.7320508076, # 1.7320508076 is approx. sin(60°)*2 41 | ).configure_view( 42 | strokeWidth=0 43 | ) 44 | -------------------------------------------------------------------------------- /altair/examples/histogram_responsive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Histogram with Responsive Bins 3 | ------------------------------ 4 | This shows an example of a histogram with bins that are responsive to a 5 | selection domain. Click and drag on the bottom panel to see the bins 6 | change on the top panel. 7 | """ 8 | # category: histograms 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.flights_5k.url 13 | 14 | brush = alt.selection_interval(encodings=['x']) 15 | 16 | base = alt.Chart(source).transform_calculate( 17 | time="hours(datum.date) + minutes(datum.date) / 60" 18 | ).mark_bar().encode( 19 | y='count():Q' 20 | ).properties( 21 | width=600, 22 | height=100 23 | ) 24 | 25 | alt.vconcat( 26 | base.encode( 27 | alt.X('time:Q', 28 | bin=alt.Bin(maxbins=30, extent=brush), 29 | scale=alt.Scale(domain=brush) 30 | ) 31 | ), 32 | base.encode( 33 | alt.X('time:Q', bin=alt.Bin(maxbins=30)), 34 | ).add_selection(brush) 35 | ) -------------------------------------------------------------------------------- /altair/examples/histogram_with_a_global_mean_overlay.py: -------------------------------------------------------------------------------- 1 | """ 2 | Histogram with a Global Mean Overlay 3 | ------------------------------------ 4 | This example shows a histogram with a global mean overlay. 5 | """ 6 | # category: histograms 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.movies.url 11 | 12 | base = alt.Chart(source) 13 | 14 | bar = base.mark_bar().encode( 15 | x=alt.X('IMDB_Rating:Q', bin=True, axis=None), 16 | y='count()' 17 | ) 18 | 19 | rule = base.mark_rule(color='red').encode( 20 | x='mean(IMDB_Rating):Q', 21 | size=alt.value(5) 22 | ) 23 | 24 | bar + rule 25 | -------------------------------------------------------------------------------- /altair/examples/horizon_graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Horizon Graph 3 | ------------- 4 | This example shows how to make a Horizon Graph with 2 layers. (See https://idl.cs.washington.edu/papers/horizon/ for more details on Horizon Graphs.) 5 | """ 6 | # category: area charts 7 | import altair as alt 8 | import pandas as pd 9 | 10 | source = pd.DataFrame([ 11 | {"x": 1, "y": 28}, {"x": 2, "y": 55}, 12 | {"x": 3, "y": 43}, {"x": 4, "y": 91}, 13 | {"x": 5, "y": 81}, {"x": 6, "y": 53}, 14 | {"x": 7, "y": 19}, {"x": 8, "y": 87}, 15 | {"x": 9, "y": 52}, {"x": 10, "y": 48}, 16 | {"x": 11, "y": 24}, {"x": 12, "y": 49}, 17 | {"x": 13, "y": 87}, {"x": 14, "y": 66}, 18 | {"x": 15, "y": 17}, {"x": 16, "y": 27}, 19 | {"x": 17, "y": 68}, {"x": 18, "y": 16}, 20 | {"x": 19, "y": 49}, {"x": 20, "y": 15} 21 | ]) 22 | 23 | area1 = alt.Chart(source).mark_area( 24 | clip=True, 25 | interpolate='monotone' 26 | ).encode( 27 | alt.X('x', scale=alt.Scale(zero=False, nice=False)), 28 | alt.Y('y', scale=alt.Scale(domain=[0, 50]), title='y'), 29 | opacity=alt.value(0.6) 30 | ).properties( 31 | width=500, 32 | height=75 33 | ) 34 | 35 | area2 = area1.encode( 36 | alt.Y('ny:Q', scale=alt.Scale(domain=[0, 50])) 37 | ).transform_calculate( 38 | "ny", alt.datum.y - 50 39 | ) 40 | 41 | area1 + area2 42 | -------------------------------------------------------------------------------- /altair/examples/horizontal_stacked_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Horizontal Stacked Bar Chart 3 | ============================ 4 | This is an example of a horizontal stacked bar chart using data which contains crop yields over different regions and different years in the 1930s. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='sum(yield)', 14 | y='variety', 15 | color='site' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/image_tooltip.py: -------------------------------------------------------------------------------- 1 | """ 2 | Image tooltip 3 | ------------- 4 | This example shows how to render images in tooltips. 5 | Either URLs or local file paths can be used to reference 6 | the images. 7 | """ 8 | # category: other charts 9 | 10 | import altair as alt 11 | import pandas as pd 12 | 13 | source = pd.DataFrame.from_records( 14 | [{'a': 1, 'b': 1, 'image': 'https://altair-viz.github.io/_static/altair-logo-light.png'}, 15 | {'a': 2, 'b': 2, 'image': 'https://avatars.githubusercontent.com/u/11796929?s=200&v=4'}] 16 | ) 17 | alt.Chart(source).mark_circle(size=200).encode( 18 | x='a', 19 | y='b', 20 | tooltip=['image'] # Must be a list for the image to render 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/interactive_brush.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive Rectangular Brush 3 | ============================= 4 | This example shows how to add a simple rectangular brush to a scatter plot. 5 | By clicking and dragging on the plot, you can highlight points within the 6 | range. 7 | """ 8 | # category: interactive charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.cars() 13 | brush = alt.selection(type='interval') 14 | 15 | alt.Chart(source).mark_point().encode( 16 | x='Horsepower:Q', 17 | y='Miles_per_Gallon:Q', 18 | color=alt.condition(brush, 'Cylinders:O', alt.value('grey')), 19 | ).add_selection(brush) 20 | -------------------------------------------------------------------------------- /altair/examples/interactive_cross_highlight.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive Chart with Cross-Highlight 3 | ====================================== 4 | This example shows an interactive chart where selections in one portion of 5 | the chart affect what is shown in other panels. Click on the bar chart to 6 | see a detail of the distribution in the upper panel. 7 | """ 8 | # category: interactive charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.movies.url 13 | 14 | pts = alt.selection(type="single", encodings=['x']) 15 | 16 | rect = alt.Chart(data.movies.url).mark_rect().encode( 17 | alt.X('IMDB_Rating:Q', bin=True), 18 | alt.Y('Rotten_Tomatoes_Rating:Q', bin=True), 19 | alt.Color('count()', 20 | scale=alt.Scale(scheme='greenblue'), 21 | legend=alt.Legend(title='Total Records') 22 | ) 23 | ) 24 | 25 | circ = rect.mark_point().encode( 26 | alt.ColorValue('grey'), 27 | alt.Size('count()', 28 | legend=alt.Legend(title='Records in Selection') 29 | ) 30 | ).transform_filter( 31 | pts 32 | ) 33 | 34 | bar = alt.Chart(source).mark_bar().encode( 35 | x='Major_Genre:N', 36 | y='count()', 37 | color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey")) 38 | ).properties( 39 | width=550, 40 | height=200 41 | ).add_selection(pts) 42 | 43 | alt.vconcat( 44 | rect + circ, 45 | bar 46 | ).resolve_legend( 47 | color="independent", 48 | size="independent" 49 | ) 50 | -------------------------------------------------------------------------------- /altair/examples/interactive_layered_crossfilter.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive Crossfilter 3 | ======================= 4 | This example shows a multi-panel view of the same data, where you can interactively 5 | select a portion of the data in any of the panels to highlight that portion in any 6 | of the other panels. 7 | """ 8 | # category: interactive charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = alt.UrlData( 13 | data.flights_2k.url, 14 | format={'parse': {'date': 'date'}} 15 | ) 16 | 17 | brush = alt.selection(type='interval', encodings=['x']) 18 | 19 | # Define the base chart, with the common parts of the 20 | # background and highlights 21 | base = alt.Chart().mark_bar().encode( 22 | x=alt.X(alt.repeat('column'), type='quantitative', bin=alt.Bin(maxbins=20)), 23 | y='count()' 24 | ).properties( 25 | width=160, 26 | height=130 27 | ) 28 | 29 | # gray background with selection 30 | background = base.encode( 31 | color=alt.value('#ddd') 32 | ).add_selection(brush) 33 | 34 | # blue highlights on the transformed data 35 | highlight = base.transform_filter(brush) 36 | 37 | # layer the two charts & repeat 38 | alt.layer( 39 | background, 40 | highlight, 41 | data=source 42 | ).transform_calculate( 43 | "time", 44 | "hours(datum.date)" 45 | ).repeat(column=["distance", "delay", "time"]) 46 | -------------------------------------------------------------------------------- /altair/examples/interactive_legend.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive Legend 3 | ------------------ 4 | The following shows how to create a chart with an interactive legend, by 5 | binding the selection to ``"legend"``. Such a binding only works with 6 | ``selection_single`` or ``selection_multi`` when projected over a single 7 | field or encoding. 8 | """ 9 | # category: interactive charts 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.unemployment_across_industries.url 14 | 15 | selection = alt.selection_multi(fields=['series'], bind='legend') 16 | 17 | alt.Chart(source).mark_area().encode( 18 | alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)), 19 | alt.Y('sum(count):Q', stack='center', axis=None), 20 | alt.Color('series:N', scale=alt.Scale(scheme='category20b')), 21 | opacity=alt.condition(selection, alt.value(1), alt.value(0.2)) 22 | ).add_selection( 23 | selection 24 | ) -------------------------------------------------------------------------------- /altair/examples/interactive_scatter_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Interactive Colored Scatterplot 3 | -------------------------------------- 4 | This example shows how to make an interactive scatterplot. 5 | """ 6 | # category: interactive charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.cars() 11 | 12 | alt.Chart(source).mark_circle().encode( 13 | x='Horsepower', 14 | y='Miles_per_Gallon', 15 | color='Origin', 16 | ).interactive() 17 | -------------------------------------------------------------------------------- /altair/examples/interval_selection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interval Selection Example 3 | ========================== 4 | 5 | This is an example of creating a stacked chart for which the domain of the 6 | top chart can be selected by interacting with the bottom chart. 7 | """ 8 | # category: area charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.sp500.url 13 | 14 | brush = alt.selection(type='interval', encodings=['x']) 15 | 16 | base = alt.Chart(source).mark_area().encode( 17 | x = 'date:T', 18 | y = 'price:Q' 19 | ).properties( 20 | width=600, 21 | height=200 22 | ) 23 | 24 | upper = base.encode( 25 | alt.X('date:T', scale=alt.Scale(domain=brush)) 26 | ) 27 | 28 | lower = base.properties( 29 | height=60 30 | ).add_selection(brush) 31 | 32 | upper & lower 33 | -------------------------------------------------------------------------------- /altair/examples/iowa_electricity.py: -------------------------------------------------------------------------------- 1 | """ 2 | Iowa's renewable energy boom 3 | ---------------------------- 4 | This example is a fully developed stacked chart using the sample dataset of Iowa's electricity sources. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source, title="Iowa's renewable energy boom").mark_area().encode( 13 | x=alt.X( 14 | "year:T", 15 | title="Year" 16 | ), 17 | y=alt.Y( 18 | "net_generation:Q", 19 | stack="normalize", 20 | title="Share of net generation", 21 | axis=alt.Axis(format=".0%"), 22 | ), 23 | color=alt.Color( 24 | "source:N", 25 | legend=alt.Legend(title="Electricity source"), 26 | ) 27 | ) 28 | -------------------------------------------------------------------------------- /altair/examples/isotype_grid.py: -------------------------------------------------------------------------------- 1 | """ 2 | Isotype Grid 3 | ------------ 4 | This example is a grid of isotype figures. 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | import pandas as pd 9 | 10 | data = pd.DataFrame([dict(id=i) for i in range(1, 101)]) 11 | 12 | person = ( 13 | "M1.7 -1.7h-0.8c0.3 -0.2 0.6 -0.5 0.6 -0.9c0 -0.6 " 14 | "-0.4 -1 -1 -1c-0.6 0 -1 0.4 -1 1c0 0.4 0.2 0.7 0.6 " 15 | "0.9h-0.8c-0.4 0 -0.7 0.3 -0.7 0.6v1.9c0 0.3 0.3 0.6 " 16 | "0.6 0.6h0.2c0 0 0 0.1 0 0.1v1.9c0 0.3 0.2 0.6 0.3 " 17 | "0.6h1.3c0.2 0 0.3 -0.3 0.3 -0.6v-1.8c0 0 0 -0.1 0 " 18 | "-0.1h0.2c0.3 0 0.6 -0.3 0.6 -0.6v-2c0.2 -0.3 -0.1 " 19 | "-0.6 -0.4 -0.6z" 20 | ) 21 | 22 | alt.Chart(data).transform_calculate( 23 | row="ceil(datum.id/10)" 24 | ).transform_calculate( 25 | col="datum.id - datum.row*10" 26 | ).mark_point( 27 | filled=True, 28 | size=50 29 | ).encode( 30 | x=alt.X("col:O", axis=None), 31 | y=alt.Y("row:O", axis=None), 32 | shape=alt.ShapeValue(person) 33 | ).properties( 34 | width=400, 35 | height=400 36 | ).configure_view( 37 | strokeWidth=0 38 | ) 39 | -------------------------------------------------------------------------------- /altair/examples/jitter_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Jitter Chart 3 | ------------ 4 | In this chart, we encode the ``Cylinders`` column from the ``cars`` dataset in the ``y``-channel. Because most cars (all but seven) in this dataset have 4, 6, or 8 cylinders, the default presentation of this data would show most of the data concentrated on three horizontal lines. Furthermore, in that default presentation, it would be difficult to gauge the relative frequencies with which different values occur (because there would be so much overlap). To compensate for this, we use the ``yOffset`` channel to incorporate a random offset (jittering). This is adapted from a corresponding Vega-Lite Example: 5 | `Dot Plot with Jittering `_. 6 | """ 7 | # category: scatter plots 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | alt.Chart(source).mark_point().encode( 14 | x='Horsepower:Q', 15 | y='Cylinders:O', 16 | yOffset='randomCalc:Q' 17 | ).transform_calculate( 18 | randomCalc='random()' 19 | ).properties( 20 | height=alt.Step(50) 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/layer_line_color_rule.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Layered Aggregates 3 | ---------------------------------- 4 | This example shows how to make a multi-series line chart of the daily closing 5 | stock prices for AAPL, AMZN, GOOG, IBM, and MSFT between 2000 and 2010, along 6 | with a layered rule showing the average values. 7 | """ 8 | # category: line charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.stocks() 13 | 14 | base = alt.Chart(source).properties(width=550) 15 | 16 | line = base.mark_line().encode( 17 | x='date', 18 | y='price', 19 | color='symbol' 20 | ) 21 | 22 | rule = base.mark_rule().encode( 23 | y='average(price)', 24 | color='symbol', 25 | size=alt.value(2) 26 | ) 27 | 28 | line + rule 29 | -------------------------------------------------------------------------------- /altair/examples/layered_area_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Layered Area Chart 3 | ------------------ 4 | This example shows a layered area chart. 5 | """ 6 | # category: area charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source).mark_area(opacity=0.3).encode( 13 | x="year:T", 14 | y=alt.Y("net_generation:Q", stack=None), 15 | color="source:N" 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/layered_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Layered Bar Chart 3 | ----------------- 4 | This example shows a segmented bar chart that is layered rather than stacked. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source).mark_bar(opacity=0.7).encode( 13 | x='year:O', 14 | y=alt.Y('net_generation:Q', stack=None), 15 | color="source", 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/layered_chart_bar_mark.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bar and Tick Chart 3 | ------------------ 4 | How to layer a tick chart on top of a bar chart. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | import pandas as pd 9 | 10 | source = pd.DataFrame({ 11 | 'project': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 12 | 'score': [25, 57, 23, 19, 8, 47, 8], 13 | 'goal': [25, 47, 30, 27, 38, 19, 4] 14 | }) 15 | 16 | bar = alt.Chart(source).mark_bar().encode( 17 | x='project', 18 | y='score' 19 | ).properties( 20 | width=alt.Step(40) # controls width of bar. 21 | ) 22 | 23 | tick = alt.Chart(source).mark_tick( 24 | color='red', 25 | thickness=2, 26 | size=40 * 0.9, # controls width of tick. 27 | ).encode( 28 | x='project', 29 | y='goal' 30 | ) 31 | 32 | bar + tick 33 | -------------------------------------------------------------------------------- /altair/examples/layered_chart_with_dual_axis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Layered chart with Dual-Axis 3 | ---------------------------- 4 | This example shows how to create a second independent y axis. 5 | """ 6 | # category: other charts 7 | 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.seattle_weather() 12 | 13 | base = alt.Chart(source).encode( 14 | alt.X('month(date):T', axis=alt.Axis(title=None)) 15 | ) 16 | 17 | area = base.mark_area(opacity=0.3, color='#57A44C').encode( 18 | alt.Y('average(temp_max)', 19 | axis=alt.Axis(title='Avg. Temperature (°C)', titleColor='#57A44C')), 20 | alt.Y2('average(temp_min)') 21 | ) 22 | 23 | line = base.mark_line(stroke='#5276A7', interpolate='monotone').encode( 24 | alt.Y('average(precipitation)', 25 | axis=alt.Axis(title='Precipitation (inches)', titleColor='#5276A7')) 26 | ) 27 | 28 | alt.layer(area, line).resolve_scale( 29 | y = 'independent' 30 | ) 31 | -------------------------------------------------------------------------------- /altair/examples/layered_heatmap_text.py: -------------------------------------------------------------------------------- 1 | """ 2 | Text over a Heatmap 3 | ------------------- 4 | 5 | An example of a layered chart of text over a heatmap using the cars dataset. 6 | """ 7 | # category: other charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | # Configure common options 14 | base = alt.Chart(source).transform_aggregate( 15 | num_cars='count()', 16 | groupby=['Origin', 'Cylinders'] 17 | ).encode( 18 | alt.X('Cylinders:O', scale=alt.Scale(paddingInner=0)), 19 | alt.Y('Origin:O', scale=alt.Scale(paddingInner=0)), 20 | ) 21 | 22 | # Configure heatmap 23 | heatmap = base.mark_rect().encode( 24 | color=alt.Color('num_cars:Q', 25 | scale=alt.Scale(scheme='viridis'), 26 | legend=alt.Legend(direction='horizontal') 27 | ) 28 | ) 29 | 30 | # Configure text 31 | text = base.mark_text(baseline='middle').encode( 32 | text='num_cars:Q', 33 | color=alt.condition( 34 | alt.datum.num_cars > 100, 35 | alt.value('black'), 36 | alt.value('white') 37 | ) 38 | ) 39 | 40 | # Draw the chart 41 | heatmap + text -------------------------------------------------------------------------------- /altair/examples/layered_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Layered Histogram 3 | ================= 4 | This example shows how to use opacity to make a layered histogram in Altair. 5 | """ 6 | # category: histograms 7 | import pandas as pd 8 | import altair as alt 9 | import numpy as np 10 | np.random.seed(42) 11 | 12 | # Generating Data 13 | source = pd.DataFrame({ 14 | 'Trial A': np.random.normal(0, 0.8, 1000), 15 | 'Trial B': np.random.normal(-2, 1, 1000), 16 | 'Trial C': np.random.normal(3, 2, 1000) 17 | }) 18 | 19 | alt.Chart(source).transform_fold( 20 | ['Trial A', 'Trial B', 'Trial C'], 21 | as_=['Experiment', 'Measurement'] 22 | ).mark_bar( 23 | opacity=0.3, 24 | binSpacing=0 25 | ).encode( 26 | alt.X('Measurement:Q', bin=alt.Bin(maxbins=100)), 27 | alt.Y('count()', stack=None), 28 | alt.Color('Experiment:N') 29 | ) 30 | -------------------------------------------------------------------------------- /altair/examples/line_chart_with_color_datum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with datum for color 3 | ------------------------------- 4 | An example of using ``datum`` and ``repeat`` to color a multi-series line chart. 5 | This is adapted from this corresponding Vega-Lite Example: 6 | `Repeat and Layer to Show Different Movie Measures `_. 7 | """ 8 | # category: line charts 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.movies() 14 | 15 | alt.Chart(source).mark_line().encode( 16 | x=alt.X("IMDB_Rating", bin=True), 17 | y=alt.Y( 18 | alt.repeat("layer"), aggregate="mean", title="Mean of US and Worldwide Gross" 19 | ), 20 | color=alt.datum(alt.repeat("layer")), 21 | ).repeat(layer=["US_Gross", "Worldwide_Gross"]) 22 | -------------------------------------------------------------------------------- /altair/examples/line_chart_with_cumsum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Cumulative Sum 3 | ------------------------------ 4 | This chart creates a simple line chart from the cumulative sum of a fields. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | alt.Chart(source).mark_line().transform_window( 13 | # Sort the data chronologically 14 | sort=[{'field': 'year'}], 15 | # Include all previous records before the current record and none after 16 | # (This is the default value so you could skip it and it would still work.) 17 | frame=[None, 0], 18 | # What to add up as you go 19 | cumulative_wheat='sum(wheat)' 20 | ).encode( 21 | x='year:O', 22 | # Plot the calculated field created by the transformation 23 | y='cumulative_wheat:Q' 24 | ).properties(width=600) -------------------------------------------------------------------------------- /altair/examples/line_chart_with_datum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with datum 3 | --------------------------------- 4 | An example of using ``datum`` to highlight certain values, including a ``DateTime`` value. 5 | This is adapted from two corresponding Vega-Lite Examples: 6 | `Highlight a Specific Value `_. 7 | """ 8 | # category: line charts 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.stocks() 14 | 15 | lines = ( 16 | alt.Chart(source) 17 | .mark_line() 18 | .encode(x="date", y="price", color="symbol") 19 | ) 20 | 21 | xrule = ( 22 | alt.Chart() 23 | .mark_rule(color="cyan", strokeWidth=2) 24 | .encode(x=alt.datum(alt.DateTime(year=2006, month="November"))) 25 | ) 26 | 27 | yrule = ( 28 | alt.Chart().mark_rule(strokeDash=[12, 6], size=2).encode(y=alt.datum(350)) 29 | ) 30 | 31 | 32 | lines + yrule + xrule 33 | -------------------------------------------------------------------------------- /altair/examples/line_chart_with_generator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Sequence Generator 3 | ---------------------------------- 4 | This examples shows how to create multiple lines using the sequence generator. 5 | """ 6 | # category: line charts 7 | 8 | import altair as alt 9 | 10 | source = alt.sequence(start=0, stop=12.7, step=0.1, as_='x') 11 | 12 | alt.Chart(source).mark_line().transform_calculate( 13 | sin='sin(datum.x)', 14 | cos='cos(datum.x)' 15 | ).transform_fold( 16 | ['sin', 'cos'] 17 | ).encode( 18 | x='x:Q', 19 | y='value:Q', 20 | color='key:N' 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/line_chart_with_points.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Points 3 | ---------------------- 4 | This chart shows a simple line chart with points marking each value. Use 5 | ``point=True`` for points with default appearance or customize it with 6 | ``OverlayMarkDef()``. 7 | """ 8 | # category: line charts 9 | import altair as alt 10 | import numpy as np 11 | import pandas as pd 12 | 13 | x = np.arange(100) 14 | source = pd.DataFrame({ 15 | 'x': x, 16 | 'f(x)': np.sin(x / 5) 17 | }) 18 | 19 | alt.Chart(source).mark_line( 20 | point=alt.OverlayMarkDef(color="red") 21 | ).encode( 22 | x='x', 23 | y='f(x)' 24 | ) 25 | -------------------------------------------------------------------------------- /altair/examples/line_percent.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Percent axis 3 | ---------------------------- 4 | This example shows how to format the tick labels of the y-axis of a chart as percentages. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.jobs.url 11 | 12 | alt.Chart(source).mark_line().encode( 13 | alt.X('year:O'), 14 | alt.Y('perc:Q', axis=alt.Axis(format='%')), 15 | color='sex:N' 16 | ).transform_filter( 17 | alt.datum.job == 'Welder' 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/line_with_ci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Confidence Interval Band 3 | ---------------------------------------- 4 | How to make a line chart with a bootstrapped 95% confidence interval band. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.cars() 11 | 12 | line = alt.Chart(source).mark_line().encode( 13 | x='Year', 14 | y='mean(Miles_per_Gallon)' 15 | ) 16 | 17 | band = alt.Chart(source).mark_errorband(extent='ci').encode( 18 | x='Year', 19 | y=alt.Y('Miles_per_Gallon', title='Miles/Gallon'), 20 | ) 21 | 22 | band + line 23 | -------------------------------------------------------------------------------- /altair/examples/line_with_log_scale.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Logarithmic Scale 3 | --------------------------------- 4 | How to make a line chart on a `Logarithmic scale `_. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.population() 11 | 12 | alt.Chart(source).mark_line().encode( 13 | x='year:O', 14 | y=alt.Y( 15 | 'sum(people)', 16 | scale=alt.Scale(type="log") # Here the scale is applied 17 | ) 18 | ) -------------------------------------------------------------------------------- /altair/examples/multi_series_line.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multi Series Line Chart 3 | ----------------------- 4 | 5 | This example shows how to make a multi series line chart of the daily closing stock prices for AAPL, AMZN, GOOG, IBM, and MSFT between 2000 and 2010. 6 | """ 7 | # category: line charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.stocks() 12 | 13 | alt.Chart(source).mark_line().encode( 14 | x='date', 15 | y='price', 16 | color='symbol', 17 | strokeDash='symbol', 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/multifeature_scatter_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multifeature Scatter Plot 3 | ========================= 4 | This example shows how to make a scatter plot with multiple feature encodings. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iris() 11 | 12 | alt.Chart(source).mark_circle().encode( 13 | alt.X('sepalLength', scale=alt.Scale(zero=False)), 14 | alt.Y('sepalWidth', scale=alt.Scale(zero=False, padding=1)), 15 | color='species', 16 | size='petalWidth' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/multiline_highlight.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multi-Line Highlight 3 | ==================== 4 | This multi-line chart uses an invisible Voronoi tessellation to handle mouseover to 5 | identify the nearest point and then highlight the line on which the point falls. 6 | It is adapted from the Vega-Lite example found at 7 | https://bl.ocks.org/amitkaps/fe4238e716db53930b2f1a70d3401701 8 | """ 9 | # category: interactive charts 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.stocks() 14 | 15 | highlight = alt.selection(type='single', on='mouseover', 16 | fields=['symbol'], nearest=True) 17 | 18 | base = alt.Chart(source).encode( 19 | x='date:T', 20 | y='price:Q', 21 | color='symbol:N' 22 | ) 23 | 24 | points = base.mark_circle().encode( 25 | opacity=alt.value(0) 26 | ).add_selection( 27 | highlight 28 | ).properties( 29 | width=600 30 | ) 31 | 32 | lines = base.mark_line().encode( 33 | size=alt.condition(~highlight, alt.value(1), alt.value(3)) 34 | ) 35 | 36 | points + lines 37 | -------------------------------------------------------------------------------- /altair/examples/multiple_marks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multiple Marks 3 | ============== 4 | This example demonstrates creating a single chart with multiple markers 5 | representing the same data. 6 | """ 7 | # category: other charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.stocks() 12 | 13 | alt.Chart(source).mark_line(point=True).encode( 14 | x='date:T', 15 | y='price:Q', 16 | color='symbol:N' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/natural_disasters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Natural Disasters 3 | ----------------- 4 | This example shows a visualization of global deaths from natural disasters. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.disasters.url 11 | 12 | alt.Chart(source).mark_circle( 13 | opacity=0.8, 14 | stroke='black', 15 | strokeWidth=1 16 | ).encode( 17 | alt.X('Year:O', axis=alt.Axis(labelAngle=0)), 18 | alt.Y('Entity:N'), 19 | alt.Size('Deaths:Q', 20 | scale=alt.Scale(range=[0, 4000]), 21 | legend=alt.Legend(title='Annual Global Deaths') 22 | ), 23 | alt.Color('Entity:N', legend=None) 24 | ).properties( 25 | width=450, 26 | height=320 27 | ).transform_filter( 28 | alt.datum.Entity != 'All natural disasters' 29 | ) 30 | -------------------------------------------------------------------------------- /altair/examples/normalized_stacked_area_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Normalized Stacked Area Chart 3 | ----------------------------- 4 | This example shows how to make a normalized stacked area chart. 5 | """ 6 | # category: area charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source).mark_area().encode( 13 | x="year:T", 14 | y=alt.Y("net_generation:Q", stack="normalize"), 15 | color="source:N" 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/normalized_stacked_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Normalized Stacked Bar Chart 3 | ---------------------------- 4 | This is an example of a normalized stacked bar chart using data which contains crop yields over different regions and different years in the 1930s. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x=alt.X('sum(yield)', stack="normalize"), 14 | y='variety', 15 | color='site' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/normed_parallel_coordinates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Normalized Parallel Coordinates Example 3 | --------------------------------------- 4 | A `Parallel Coordinates `_ 5 | chart is a chart that lets you visualize the individual data points by drawing 6 | a single line for each of them. 7 | 8 | Such a chart can be created in Altair by first transforming the data into a 9 | suitable representation. 10 | 11 | This example shows a modified parallel coordinates chart with the Iris dataset, 12 | where the y-axis shows the value after min-max rather than the raw value. It's a 13 | simplified Altair version of `the VegaLite version `_ 14 | """ 15 | # category: other charts 16 | import altair as alt 17 | from vega_datasets import data 18 | from altair import datum 19 | 20 | source = data.iris() 21 | 22 | alt.Chart(source).transform_window( 23 | index='count()' 24 | ).transform_fold( 25 | ['petalLength', 'petalWidth', 'sepalLength', 'sepalWidth'] 26 | ).transform_joinaggregate( 27 | min='min(value)', 28 | max='max(value)', 29 | groupby=['key'] 30 | ).transform_calculate( 31 | minmax_value=(datum.value-datum.min)/(datum.max-datum.min), 32 | mid=(datum.min+datum.max)/2 33 | ).mark_line().encode( 34 | x='key:N', 35 | y='minmax_value:Q', 36 | color='species:N', 37 | detail='index:N', 38 | opacity=alt.value(0.5) 39 | ).properties(width=500) 40 | 41 | 42 | -------------------------------------------------------------------------------- /altair/examples/one_dot_per_zipcode.py: -------------------------------------------------------------------------------- 1 | """ 2 | One Dot Per Zipcode 3 | ----------------------- 4 | This example shows a geographical plot with one dot per zipcode. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | # Since the data is more than 5,000 rows we'll import it from a URL 11 | source = data.zipcodes.url 12 | 13 | alt.Chart(source).transform_calculate( 14 | "leading digit", alt.expr.substring(alt.datum.zip_code, 0, 1) 15 | ).mark_circle(size=3).encode( 16 | longitude='longitude:Q', 17 | latitude='latitude:Q', 18 | color='leading digit:N', 19 | tooltip='zip_code:N' 20 | ).project( 21 | type='albersUsa' 22 | ).properties( 23 | width=650, 24 | height=400 25 | ) 26 | -------------------------------------------------------------------------------- /altair/examples/pacman_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pacman Chart 3 | ------------ 4 | Chart made using ``mark_arc`` and constant values. 5 | This could also be made using 6 | ``alt.Chart(source).mark_arc(color = "gold", theta = (5/8)*np.pi, theta2 = (19/8)*np.pi,radius=100)``. 7 | """ 8 | # category: circular plots 9 | 10 | import numpy as np 11 | import altair as alt 12 | 13 | alt.Chart().mark_arc(color="gold").encode( 14 | theta=alt.datum((5 / 8) * np.pi, scale=None), 15 | theta2=alt.datum((19 / 8) * np.pi), 16 | radius=alt.datum(100, scale=None), 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/parallel_coordinates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parallel Coordinates Example 3 | ---------------------------- 4 | A `Parallel Coordinates `_ 5 | chart is a chart that lets you visualize the individual data points by drawing 6 | a single line for each of them. 7 | Such a chart can be created in Altair by first transforming the data into a 8 | suitable representation. 9 | This example shows a parallel coordinates chart with the Iris dataset. 10 | """ 11 | # category: other charts 12 | 13 | import altair as alt 14 | from vega_datasets import data 15 | 16 | source = data.iris() 17 | 18 | alt.Chart(source).transform_window( 19 | index='count()' 20 | ).transform_fold( 21 | ['petalLength', 'petalWidth', 'sepalLength', 'sepalWidth'] 22 | ).mark_line().encode( 23 | x='key:N', 24 | y='value:Q', 25 | color='species:N', 26 | detail='index:N', 27 | opacity=alt.value(0.5) 28 | ).properties(width=500) 29 | -------------------------------------------------------------------------------- /altair/examples/percentage_of_total.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculating Percentage of Total 3 | ------------------------------- 4 | This chart demonstrates how to use a joinaggregate transform to display 5 | data values as a percentage of total. 6 | """ 7 | # category: bar charts 8 | import altair as alt 9 | import pandas as pd 10 | 11 | source = pd.DataFrame({'Activity': ['Sleeping', 'Eating', 'TV', 'Work', 'Exercise'], 12 | 'Time': [8, 2, 4, 8, 2]}) 13 | 14 | alt.Chart(source).transform_joinaggregate( 15 | TotalTime='sum(Time)', 16 | ).transform_calculate( 17 | PercentOfTotal="datum.Time / datum.TotalTime" 18 | ).mark_bar().encode( 19 | alt.X('PercentOfTotal:Q', axis=alt.Axis(format='.0%')), 20 | y='Activity:N' 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/pie_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pie Chart 3 | --------- 4 | This example shows how to make a Pie Chart using ``mark_arc``. 5 | This is adapted from a corresponding Vega-Lite Example: 6 | `Pie Chart `_. 7 | """ 8 | # category: circular plots 9 | 10 | import pandas as pd 11 | import altair as alt 12 | 13 | source = pd.DataFrame({"category": [1, 2, 3, 4, 5, 6], "value": [4, 6, 10, 3, 7, 8]}) 14 | 15 | alt.Chart(source).mark_arc().encode( 16 | theta=alt.Theta(field="value", type="quantitative"), 17 | color=alt.Color(field="category", type="nominal"), 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/pie_chart_with_labels.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pie Chart with Labels 3 | --------------------- 4 | This example shows how to layer text over arc marks (``mark_arc``) to label pie charts. 5 | This is adapted from a corresponding Vega-Lite Example: 6 | `Pie Chart with Labels `_. 7 | """ 8 | # category: circular plots 9 | 10 | import pandas as pd 11 | import altair as alt 12 | 13 | source = pd.DataFrame( 14 | {"category": ["a", "b", "c", "d", "e", "f"], "value": [4, 6, 10, 3, 7, 8]} 15 | ) 16 | 17 | base = alt.Chart(source).encode( 18 | theta=alt.Theta("value:Q", stack=True), color=alt.Color("category:N", legend=None) 19 | ) 20 | 21 | pie = base.mark_arc(outerRadius=120) 22 | text = base.mark_text(radius=140, size=20).encode(text="category:N") 23 | 24 | pie + text 25 | -------------------------------------------------------------------------------- /altair/examples/poly_fit_regression.py: -------------------------------------------------------------------------------- 1 | """ 2 | Polynomial Fit Plot with Regression Transform 3 | ============================================= 4 | This example shows how to overlay data with multiple fitted polynomials using 5 | the regression transform. 6 | """ 7 | # category: scatter plots 8 | 9 | import numpy as np 10 | import pandas as pd 11 | import altair as alt 12 | 13 | # Generate some random data 14 | rng = np.random.RandomState(1) 15 | x = rng.rand(40) ** 2 16 | y = 10 - 1.0 / (x + 0.1) + rng.randn(40) 17 | source = pd.DataFrame({"x": x, "y": y}) 18 | 19 | # Define the degree of the polynomial fits 20 | degree_list = [1, 3, 5] 21 | 22 | base = alt.Chart(source).mark_circle(color="black").encode( 23 | alt.X("x"), alt.Y("y") 24 | ) 25 | 26 | polynomial_fit = [ 27 | base.transform_regression( 28 | "x", "y", method="poly", order=order, as_=["x", str(order)] 29 | ) 30 | .mark_line() 31 | .transform_fold([str(order)], as_=["degree", "y"]) 32 | .encode(alt.Color("degree:N")) 33 | for order in degree_list 34 | ] 35 | 36 | alt.layer(base, *polynomial_fit) 37 | -------------------------------------------------------------------------------- /altair/examples/pyramid.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pyramid Pie Chart 3 | ----------------- 4 | Altair reproduction of http://robslink.com/SAS/democd91/pyramid_pie.htm 5 | """ 6 | import altair as alt 7 | import pandas as pd 8 | 9 | category = ['Sky', 'Shady side of a pyramid', 'Sunny side of a pyramid'] 10 | color = ["#416D9D", "#674028", "#DEAC58"] 11 | df = pd.DataFrame({'category': category, 'value': [75, 10, 15]}) 12 | 13 | alt.Chart(df).mark_arc(outerRadius=80).encode( 14 | alt.Theta('value:Q', scale=alt.Scale(range=[2.356, 8.639])), 15 | alt.Color('category:N', 16 | scale=alt.Scale(domain=category, range=color), 17 | legend=alt.Legend(title=None, orient='none', legendX=160, legendY=50)), 18 | order='value:Q' 19 | ).properties(width=150, height=150).configure_view(strokeOpacity=0) -------------------------------------------------------------------------------- /altair/examples/radial_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Radial Chart 3 | ------------ 4 | This radial plot uses both angular and radial extent to convey multiple dimensions of data. 5 | This is adapted from a corresponding Vega-Lite Example: 6 | `Radial Plot `_. 7 | """ 8 | # category: circular plots 9 | 10 | import pandas as pd 11 | import altair as alt 12 | 13 | source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]}) 14 | 15 | base = alt.Chart(source).encode( 16 | theta=alt.Theta("values:Q", stack=True), 17 | radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)), 18 | color="values:N", 19 | ) 20 | 21 | c1 = base.mark_arc(innerRadius=20, stroke="#fff") 22 | 23 | c2 = base.mark_text(radiusOffset=10).encode(text="values:Q") 24 | 25 | c1 + c2 26 | -------------------------------------------------------------------------------- /altair/examples/ranged_dot_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ranged Dot Plot 3 | ----------------- 4 | This example shows a ranged dot plot that uses 'layer' to convey changing life expectancy for the five most populous countries (between 1955 and 2000). 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.countries.url 11 | 12 | chart = alt.layer( 13 | data=source 14 | ).transform_filter( 15 | filter={"field": 'country', 16 | "oneOf": ["China", "India", "United States", "Indonesia", "Brazil"]} 17 | ).transform_filter( 18 | filter={'field': 'year', 19 | "oneOf": [1955, 2000]} 20 | ) 21 | 22 | chart += alt.Chart().mark_line(color='#db646f').encode( 23 | x='life_expect:Q', 24 | y='country:N', 25 | detail='country:N' 26 | ) 27 | # Add points for life expectancy in 1955 & 2000 28 | chart += alt.Chart().mark_point( 29 | size=100, 30 | opacity=1, 31 | filled=True 32 | ).encode( 33 | x='life_expect:Q', 34 | y='country:N', 35 | color=alt.Color('year:O', 36 | scale=alt.Scale( 37 | domain=['1955', '2000'], 38 | range=['#e6959c', '#911a24'] 39 | ) 40 | ) 41 | ).interactive() 42 | 43 | chart 44 | -------------------------------------------------------------------------------- /altair/examples/ridgeline_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ridgeline plot Example 3 | ---------------------- 4 | A `Ridgeline plot `_ 5 | chart is a chart that lets you visualize distribution of a numeric value for 6 | several groups. 7 | 8 | Such a chart can be created in Altair by first transforming the data into a 9 | suitable representation. 10 | 11 | """ 12 | # category: other charts 13 | import altair as alt 14 | from vega_datasets import data 15 | 16 | source = data.seattle_weather.url 17 | 18 | step = 20 19 | overlap = 1 20 | 21 | alt.Chart(source, height=step).transform_timeunit( 22 | Month='month(date)' 23 | ).transform_joinaggregate( 24 | mean_temp='mean(temp_max)', groupby=['Month'] 25 | ).transform_bin( 26 | ['bin_max', 'bin_min'], 'temp_max' 27 | ).transform_aggregate( 28 | value='count()', groupby=['Month', 'mean_temp', 'bin_min', 'bin_max'] 29 | ).transform_impute( 30 | impute='value', groupby=['Month', 'mean_temp'], key='bin_min', value=0 31 | ).mark_area( 32 | interpolate='monotone', 33 | fillOpacity=0.8, 34 | stroke='lightgray', 35 | strokeWidth=0.5 36 | ).encode( 37 | alt.X('bin_min:Q', bin='binned', title='Maximum Daily Temperature (C)'), 38 | alt.Y( 39 | 'value:Q', 40 | scale=alt.Scale(range=[step, -step * overlap]), 41 | axis=None 42 | ), 43 | alt.Fill( 44 | 'mean_temp:Q', 45 | legend=None, 46 | scale=alt.Scale(domain=[30, 5], scheme='redyellowblue') 47 | ) 48 | ).facet( 49 | row=alt.Row( 50 | 'Month:T', 51 | title=None, 52 | header=alt.Header(labelAngle=0, labelAlign='right', format='%B') 53 | ) 54 | ).properties( 55 | title='Seattle Weather', 56 | bounds='flush' 57 | ).configure_facet( 58 | spacing=0 59 | ).configure_view( 60 | stroke=None 61 | ).configure_title( 62 | anchor='end' 63 | ) 64 | -------------------------------------------------------------------------------- /altair/examples/scatter_href.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Plot with Href 3 | ---------------------- 4 | This example shows a scatter plot with an ``href`` encoding constructed from 5 | the car name. With this encoding, you can click on any of the points to open 6 | a google search for the car name. 7 | """ 8 | # category: scatter plots 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.cars() 14 | 15 | alt.Chart(source).transform_calculate( 16 | url='https://www.google.com/search?q=' + alt.datum.Name 17 | ).mark_point().encode( 18 | x='Horsepower:Q', 19 | y='Miles_per_Gallon:Q', 20 | color='Origin:N', 21 | href='url:N', 22 | tooltip=['Name:N', 'url:N'] 23 | ) 24 | -------------------------------------------------------------------------------- /altair/examples/scatter_linked_brush.py: -------------------------------------------------------------------------------- 1 | """ 2 | Multi-panel Scatter Plot with Linked Brushing 3 | --------------------------------------------- 4 | This is an example of using an interval selection to control the color of 5 | points across multiple panels. 6 | """ 7 | # category: interactive charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | brush = alt.selection(type='interval', resolve='global') 14 | 15 | base = alt.Chart(source).mark_point().encode( 16 | y='Miles_per_Gallon', 17 | color=alt.condition(brush, 'Origin', alt.ColorValue('gray')), 18 | ).add_selection( 19 | brush 20 | ).properties( 21 | width=250, 22 | height=250 23 | ) 24 | 25 | base.encode(x='Horsepower') | base.encode(x='Acceleration') 26 | -------------------------------------------------------------------------------- /altair/examples/scatter_linked_table.py: -------------------------------------------------------------------------------- 1 | """ 2 | Brushing Scatter Plot to show data on a table 3 | --------------------------------------------- 4 | A scatter plot of the cars dataset, with data tables for horsepower, MPG, and origin. 5 | The tables update to reflect the selection on the scatter plot. 6 | """ 7 | # category: scatter plots 8 | 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.cars() 13 | 14 | # Brush for selection 15 | brush = alt.selection(type='interval') 16 | 17 | # Scatter Plot 18 | points = alt.Chart(source).mark_point().encode( 19 | x='Horsepower:Q', 20 | y='Miles_per_Gallon:Q', 21 | color=alt.condition(brush, 'Cylinders:O', alt.value('grey')) 22 | ).add_selection(brush) 23 | 24 | # Base chart for data tables 25 | ranked_text = alt.Chart(source).mark_text().encode( 26 | y=alt.Y('row_number:O',axis=None) 27 | ).transform_window( 28 | row_number='row_number()' 29 | ).transform_filter( 30 | brush 31 | ).transform_window( 32 | rank='rank(row_number)' 33 | ).transform_filter( 34 | alt.datum.rank<20 35 | ) 36 | 37 | # Data Tables 38 | horsepower = ranked_text.encode(text='Horsepower:N').properties(title='Horsepower') 39 | mpg = ranked_text.encode(text='Miles_per_Gallon:N').properties(title='MPG') 40 | origin = ranked_text.encode(text='Origin:N').properties(title='Origin') 41 | text = alt.hconcat(horsepower, mpg, origin) # Combine data tables 42 | 43 | # Build chart 44 | alt.hconcat( 45 | points, 46 | text 47 | ).resolve_legend( 48 | color="independent" 49 | ) 50 | -------------------------------------------------------------------------------- /altair/examples/scatter_marginal_hist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Facetted Scatterplot with marginal histograms 3 | --------------------------------------------- 4 | This example demonstrates how to generate a facetted scatterplot, 5 | with marginal facetted histograms, and how to share their respective 6 | - x,some y-limits. 7 | """ 8 | # category: other charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.iris() 13 | 14 | base = alt.Chart(source) 15 | 16 | xscale = alt.Scale(domain=(4.0, 8.0)) 17 | yscale = alt.Scale(domain=(1.9, 4.55)) 18 | 19 | bar_args = {'opacity': .3, 'binSpacing': 0} 20 | 21 | points = base.mark_circle().encode( 22 | alt.X('sepalLength', scale=xscale), 23 | alt.Y('sepalWidth', scale=yscale), 24 | color='species', 25 | ) 26 | 27 | top_hist = base.mark_bar(**bar_args).encode( 28 | alt.X('sepalLength:Q', 29 | # when using bins, the axis scale is set through 30 | # the bin extent, so we do not specify the scale here 31 | # (which would be ignored anyway) 32 | bin=alt.Bin(maxbins=20, extent=xscale.domain), 33 | stack=None, 34 | title='' 35 | ), 36 | alt.Y('count()', stack=None, title=''), 37 | alt.Color('species:N'), 38 | ).properties(height=60) 39 | 40 | right_hist = base.mark_bar(**bar_args).encode( 41 | alt.Y('sepalWidth:Q', 42 | bin=alt.Bin(maxbins=20, extent=yscale.domain), 43 | stack=None, 44 | title='', 45 | ), 46 | alt.X('count()', stack=None, title=''), 47 | alt.Color('species:N'), 48 | ).properties(width=60) 49 | 50 | top_hist & (points | right_hist) 51 | -------------------------------------------------------------------------------- /altair/examples/scatter_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Matrix 3 | -------------- 4 | An example of using a RepeatChart to construct a multi-panel scatter plot 5 | with linked panning and zooming. 6 | """ 7 | # category: scatter plots 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | alt.Chart(source).mark_circle().encode( 14 | alt.X(alt.repeat("column"), type='quantitative'), 15 | alt.Y(alt.repeat("row"), type='quantitative'), 16 | color='Origin:N' 17 | ).properties( 18 | width=150, 19 | height=150 20 | ).repeat( 21 | row=['Horsepower', 'Acceleration', 'Miles_per_Gallon'], 22 | column=['Miles_per_Gallon', 'Acceleration', 'Horsepower'] 23 | ).interactive() 24 | -------------------------------------------------------------------------------- /altair/examples/scatter_qq.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quantile-Quantile Plot 3 | ---------------------- 4 | A quantile-quantile plot comparing input data to theoretical distributions. 5 | """ 6 | # category: scatter plots 7 | 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.normal_2d.url 12 | 13 | base = alt.Chart(source).transform_quantile( 14 | 'u', 15 | step=0.01, 16 | as_ = ['p', 'v'] 17 | ).transform_calculate( 18 | uniform = 'quantileUniform(datum.p)', 19 | normal = 'quantileNormal(datum.p)' 20 | ).mark_point().encode( 21 | alt.Y('v:Q') 22 | ) 23 | 24 | base.encode(x='uniform:Q') | base.encode(x='normal:Q') 25 | -------------------------------------------------------------------------------- /altair/examples/scatter_tooltips.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Scatter Plot with Tooltips 3 | --------------------------------- 4 | A scatter plot of the cars dataset, with tooltips showing selected column 5 | values when you hover over points. We make the points larger so that it is 6 | easier to hover over them. 7 | """ 8 | # category: simple charts 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.cars() 14 | 15 | alt.Chart(source).mark_circle(size=60).encode( 16 | x='Horsepower', 17 | y='Miles_per_Gallon', 18 | color='Origin', 19 | tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon'] 20 | ).interactive() 21 | -------------------------------------------------------------------------------- /altair/examples/scatter_with_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Plot and Histogram with Interval Selection 3 | ================================================== 4 | 5 | This example shows how to link a scatter plot and a histogram 6 | together such that an interval selection in the histogram will 7 | plot the selected values in the scatter plot. 8 | 9 | Note that both subplots need to know about the `mbin` field created 10 | by the `transform_bin` method. In order to achieve this, the data is 11 | not passed to the `Chart()` instances creating the subplots, but 12 | directly in the `hconcat()` function, which joins the two plots together. 13 | """ 14 | # category: interactive charts 15 | 16 | import altair as alt 17 | import pandas as pd 18 | import numpy as np 19 | 20 | x = np.random.normal(size=100) 21 | y = np.random.normal(size=100) 22 | 23 | m = np.random.normal(15, 1, size=100) 24 | 25 | source = pd.DataFrame({"x": x, "y":y, "m":m}) 26 | 27 | # interval selection in the scatter plot 28 | pts = alt.selection(type="interval", encodings=["x"]) 29 | 30 | # left panel: scatter plot 31 | points = alt.Chart().mark_point(filled=True, color="black").encode( 32 | x='x', 33 | y='y' 34 | ).transform_filter( 35 | pts 36 | ).properties( 37 | width=300, 38 | height=300 39 | ) 40 | 41 | # right panel: histogram 42 | mag = alt.Chart().mark_bar().encode( 43 | x='mbin:N', 44 | y="count()", 45 | color=alt.condition(pts, alt.value("black"), alt.value("lightgray")) 46 | ).properties( 47 | width=300, 48 | height=300 49 | ).add_selection(pts) 50 | 51 | # build the chart: 52 | alt.hconcat( 53 | points, 54 | mag, 55 | data=source 56 | ).transform_bin( 57 | "mbin", 58 | field="m", 59 | bin=alt.Bin(maxbins=20) 60 | ) 61 | -------------------------------------------------------------------------------- /altair/examples/scatter_with_labels.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Scatter Plot with Labels 3 | =============================== 4 | This example shows a basic scatter plot with labels created with Altair. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | import pandas as pd 9 | 10 | source = pd.DataFrame({ 11 | 'x': [1, 3, 5, 7, 9], 12 | 'y': [1, 3, 5, 7, 9], 13 | 'label': ['A', 'B', 'C', 'D', 'E'] 14 | }) 15 | 16 | points = alt.Chart(source).mark_point().encode( 17 | x='x:Q', 18 | y='y:Q' 19 | ) 20 | 21 | text = points.mark_text( 22 | align='left', 23 | baseline='middle', 24 | dx=7 25 | ).encode( 26 | text='label' 27 | ) 28 | 29 | points + text 30 | -------------------------------------------------------------------------------- /altair/examples/scatter_with_loess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Plot with LOESS Lines 3 | ----------------------------- 4 | This example shows how to add a trend line to a scatter plot using 5 | the LOESS transform (LOcally Estimated Scatterplot Smoothing). 6 | """ 7 | # category: scatter plots 8 | 9 | import altair as alt 10 | import pandas as pd 11 | import numpy as np 12 | 13 | np.random.seed(1) 14 | 15 | source = pd.DataFrame({ 16 | 'x': np.arange(100), 17 | 'A': np.random.randn(100).cumsum(), 18 | 'B': np.random.randn(100).cumsum(), 19 | 'C': np.random.randn(100).cumsum(), 20 | }) 21 | 22 | base = alt.Chart(source).mark_circle(opacity=0.5).transform_fold( 23 | fold=['A', 'B', 'C'], 24 | as_=['category', 'y'] 25 | ).encode( 26 | alt.X('x:Q'), 27 | alt.Y('y:Q'), 28 | alt.Color('category:N') 29 | ) 30 | 31 | base + base.transform_loess('x', 'y', groupby=['category']).mark_line(size=4) 32 | -------------------------------------------------------------------------------- /altair/examples/scatter_with_minimap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Plot with Minimap 3 | ------------------------- 4 | This example shows how to create a miniature version of a plot 5 | such that creating a selection in the miniature version 6 | adjusts the axis limits in another, more detailed view. 7 | """ 8 | # category: scatter plots 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | source = data.seattle_weather() 14 | 15 | zoom = alt.selection_interval(encodings=["x", "y"]) 16 | 17 | minimap = ( 18 | alt.Chart(source) 19 | .mark_point() 20 | .add_selection(zoom) 21 | .encode( 22 | x="date:T", 23 | y="temp_max:Q", 24 | color=alt.condition(zoom, "weather", alt.value("lightgray")), 25 | ) 26 | .properties( 27 | width=200, 28 | height=200, 29 | title="Minimap -- click and drag to zoom in the detail view", 30 | ) 31 | ) 32 | 33 | detail = ( 34 | alt.Chart(source) 35 | .mark_point() 36 | .encode( 37 | x=alt.X( 38 | "date:T", scale=alt.Scale(domain={"param": zoom.name, "encoding": "x"}) 39 | ), 40 | y=alt.Y( 41 | "temp_max:Q", 42 | scale=alt.Scale(domain={"param": zoom.name, "encoding": "y"}), 43 | ), 44 | color="weather", 45 | ) 46 | .properties(width=600, height=400, title="Seattle weather -- detail view") 47 | ) 48 | 49 | detail | minimap 50 | -------------------------------------------------------------------------------- /altair/examples/scatter_with_rolling_mean.py: -------------------------------------------------------------------------------- 1 | """ 2 | Scatter Plot with Rolling Mean 3 | ------------------------------ 4 | A scatter plot with a rolling mean overlay. In this example a 30 day window 5 | is used to calculate the mean of the maximum temperature around each date. 6 | """ 7 | # category: scatter plots 8 | 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.seattle_weather() 13 | 14 | line = alt.Chart(source).mark_line( 15 | color='red', 16 | size=3 17 | ).transform_window( 18 | rolling_mean='mean(temp_max)', 19 | frame=[-15, 15] 20 | ).encode( 21 | x='date:T', 22 | y='rolling_mean:Q' 23 | ) 24 | 25 | points = alt.Chart(source).mark_point().encode( 26 | x='date:T', 27 | y=alt.Y('temp_max:Q', 28 | axis=alt.Axis(title='Max Temp')) 29 | ) 30 | 31 | points + line 32 | -------------------------------------------------------------------------------- /altair/examples/seattle_weather_interactive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Seattle Weather Interactive 3 | =========================== 4 | This chart provides an interactive exploration of Seattle weather over the 5 | course of the year. It includes a one-axis brush selection to easily 6 | see the distribution of weather types in a particular date range. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.seattle_weather() 13 | 14 | scale = alt.Scale(domain=['sun', 'fog', 'drizzle', 'rain', 'snow'], 15 | range=['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd']) 16 | color = alt.Color('weather:N', scale=scale) 17 | 18 | # We create two selections: 19 | # - a brush that is active on the top panel 20 | # - a multi-click that is active on the bottom panel 21 | brush = alt.selection_interval(encodings=['x']) 22 | click = alt.selection_multi(encodings=['color']) 23 | 24 | # Top panel is scatter plot of temperature vs time 25 | points = alt.Chart().mark_point().encode( 26 | alt.X('monthdate(date):T', title='Date'), 27 | alt.Y('temp_max:Q', 28 | title='Maximum Daily Temperature (C)', 29 | scale=alt.Scale(domain=[-5, 40]) 30 | ), 31 | color=alt.condition(brush, color, alt.value('lightgray')), 32 | size=alt.Size('precipitation:Q', scale=alt.Scale(range=[5, 200])) 33 | ).properties( 34 | width=550, 35 | height=300 36 | ).add_selection( 37 | brush 38 | ).transform_filter( 39 | click 40 | ) 41 | 42 | # Bottom panel is a bar chart of weather type 43 | bars = alt.Chart().mark_bar().encode( 44 | x='count()', 45 | y='weather:N', 46 | color=alt.condition(click, color, alt.value('lightgray')), 47 | ).transform_filter( 48 | brush 49 | ).properties( 50 | width=550, 51 | ).add_selection( 52 | click 53 | ) 54 | 55 | alt.vconcat( 56 | points, 57 | bars, 58 | data=source, 59 | title="Seattle Weather: 2012-2015" 60 | ) 61 | -------------------------------------------------------------------------------- /altair/examples/select_mark_area.py: -------------------------------------------------------------------------------- 1 | """ 2 | Using Selection Interval with mark_area 3 | ========================================= 4 | 5 | Because area is considered one object, just using the plain 6 | selector will select the entire area instead of just one part of it. 7 | 8 | This example shows how to use two areas, one on top of the other, and a 9 | `transform_filter` to fake out this effect. 10 | 11 | """ 12 | # category: interactive charts 13 | import altair as alt 14 | from vega_datasets import data 15 | 16 | source = data.unemployment_across_industries.url 17 | 18 | base = alt.Chart(source).mark_area( 19 | color='goldenrod', 20 | opacity=0.3 21 | ).encode( 22 | x='yearmonth(date):T', 23 | y='sum(count):Q', 24 | ) 25 | 26 | brush = alt.selection_interval(encodings=['x'],empty='all') 27 | background = base.add_selection(brush) 28 | selected = base.transform_filter(brush).mark_area(color='goldenrod') 29 | 30 | background + selected 31 | -------------------------------------------------------------------------------- /altair/examples/selection_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Selection Histogram 3 | =================== 4 | This chart shows an example of using an interval selection to filter the 5 | contents of an attached histogram, allowing the user to see the proportion 6 | of items in each category within the selection. 7 | """ 8 | # category: interactive charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.cars() 13 | 14 | brush = alt.selection(type='interval') 15 | 16 | points = alt.Chart(source).mark_point().encode( 17 | x='Horsepower:Q', 18 | y='Miles_per_Gallon:Q', 19 | color=alt.condition(brush, 'Origin:N', alt.value('lightgray')) 20 | ).add_selection( 21 | brush 22 | ) 23 | 24 | bars = alt.Chart(source).mark_bar().encode( 25 | y='Origin:N', 26 | color='Origin:N', 27 | x='count(Origin):Q' 28 | ).transform_filter( 29 | brush 30 | ) 31 | 32 | points & bars 33 | -------------------------------------------------------------------------------- /altair/examples/selection_layer_bar_month.py: -------------------------------------------------------------------------------- 1 | """ 2 | Interactive Average 3 | =================== 4 | The plot below uses an interval selection, which causes the chart to include an interactive brush 5 | (shown in grey). The brush selection parameterizes the red guideline, which visualizes the average 6 | value within the selected interval. 7 | """ 8 | # category: interactive charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.seattle_weather() 13 | brush = alt.selection(type='interval', encodings=['x']) 14 | 15 | bars = alt.Chart().mark_bar().encode( 16 | x='month(date):O', 17 | y='mean(precipitation):Q', 18 | opacity=alt.condition(brush, alt.OpacityValue(1), alt.OpacityValue(0.7)), 19 | ).add_selection( 20 | brush 21 | ) 22 | 23 | line = alt.Chart().mark_rule(color='firebrick').encode( 24 | y='mean(precipitation):Q', 25 | size=alt.SizeValue(3) 26 | ).transform_filter( 27 | brush 28 | ) 29 | 30 | alt.layer(bars, line, data=source) 31 | -------------------------------------------------------------------------------- /altair/examples/simple_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Bar Chart 3 | ================ 4 | This example shows a basic bar chart created with Altair. 5 | """ 6 | # category: simple charts 7 | import altair as alt 8 | import pandas as pd 9 | 10 | source = pd.DataFrame({ 11 | 'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 12 | 'b': [28, 55, 43, 91, 81, 53, 19, 87, 52] 13 | }) 14 | 15 | alt.Chart(source).mark_bar().encode( 16 | x='a', 17 | y='b' 18 | ) 19 | -------------------------------------------------------------------------------- /altair/examples/simple_heatmap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Heatmap 3 | -------------- 4 | This example shows a simple heatmap for showing gridded data. 5 | """ 6 | # category: simple charts 7 | import altair as alt 8 | import numpy as np 9 | import pandas as pd 10 | 11 | # Compute x^2 + y^2 across a 2D grid 12 | x, y = np.meshgrid(range(-5, 5), range(-5, 5)) 13 | z = x ** 2 + y ** 2 14 | 15 | # Convert this grid to columnar data expected by Altair 16 | source = pd.DataFrame({'x': x.ravel(), 17 | 'y': y.ravel(), 18 | 'z': z.ravel()}) 19 | 20 | alt.Chart(source).mark_rect().encode( 21 | x='x:O', 22 | y='y:O', 23 | color='z:Q' 24 | ) 25 | -------------------------------------------------------------------------------- /altair/examples/simple_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Histogram 3 | ---------------- 4 | This example shows how to make a basic histogram, based on the vega-lite docs 5 | https://vega.github.io/vega-lite/examples/histogram.html 6 | """ 7 | # category: simple charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.movies.url 12 | 13 | alt.Chart(source).mark_bar().encode( 14 | alt.X("IMDB_Rating:Q", bin=True), 15 | y='count()', 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/simple_line_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Line Chart 3 | ----------------- 4 | This chart shows the most basic line chart, made from a dataframe with two 5 | columns. 6 | """ 7 | # category: simple charts 8 | 9 | import altair as alt 10 | import numpy as np 11 | import pandas as pd 12 | 13 | x = np.arange(100) 14 | source = pd.DataFrame({ 15 | 'x': x, 16 | 'f(x)': np.sin(x / 5) 17 | }) 18 | 19 | alt.Chart(source).mark_line().encode( 20 | x='x', 21 | y='f(x)' 22 | ) 23 | -------------------------------------------------------------------------------- /altair/examples/simple_scatter_with_errorbars.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Scatter Plot with Errorbars 3 | ---------------------------------- 4 | A simple scatter plot of a data set with errorbars. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | import pandas as pd 9 | import numpy as np 10 | 11 | # generate some data points with uncertainties 12 | np.random.seed(0) 13 | x = [1, 2, 3, 4, 5] 14 | y = np.random.normal(10, 0.5, size=len(x)) 15 | yerr = 0.2 16 | 17 | # set up data frame 18 | source = pd.DataFrame({"x": x, "y": y, "yerr": yerr}) 19 | 20 | # the base chart 21 | base = alt.Chart(source).transform_calculate( 22 | ymin="datum.y-datum.yerr", 23 | ymax="datum.y+datum.yerr" 24 | ) 25 | 26 | # generate the points 27 | points = base.mark_point( 28 | filled=True, 29 | size=50, 30 | color='black' 31 | ).encode( 32 | x=alt.X('x', scale=alt.Scale(domain=(0, 6))), 33 | y=alt.Y('y', scale=alt.Scale(zero=False)) 34 | ) 35 | 36 | # generate the error bars 37 | errorbars = base.mark_errorbar().encode( 38 | x="x", 39 | y="ymin:Q", 40 | y2="ymax:Q" 41 | ) 42 | 43 | points + errorbars 44 | -------------------------------------------------------------------------------- /altair/examples/simple_stacked_area_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Stacked Area Chart 3 | ------------------------- 4 | This example shows how to make a simple stacked area chart. 5 | """ 6 | # category: simple charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source).mark_area().encode( 13 | x="year:T", 14 | y="net_generation:Q", 15 | color="source:N" 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/slider_cutoff.py: -------------------------------------------------------------------------------- 1 | """ 2 | Slider Cutoff 3 | ============= 4 | This example shows how to bind a variable parameter to a slider, and how to use the corresponding bound value to color data points. This example is based on an example from the Altair 4 documentation for Interactions, in which the interactivity was accomplished using a selection. The version below has been simplified significantly through the use of a variable parameter. Variable parameters were added in Altair 5. 5 | """ 6 | # category: interactive charts 7 | import altair as alt 8 | import pandas as pd 9 | import numpy as np 10 | 11 | rand = np.random.RandomState(42) 12 | 13 | df = pd.DataFrame({ 14 | 'xval': range(100), 15 | 'yval': rand.randn(100).cumsum() 16 | }) 17 | 18 | slider = alt.binding_range(min=0, max=100, step=1) 19 | cutoff = alt.parameter(bind=slider, value=50) 20 | 21 | alt.Chart(df).mark_point().encode( 22 | x='xval', 23 | y='yval', 24 | color=alt.condition( 25 | alt.datum.xval < cutoff, 26 | alt.value('red'), alt.value('blue') 27 | ) 28 | ).add_parameter( 29 | cutoff 30 | ) -------------------------------------------------------------------------------- /altair/examples/slope_graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Slope Graph 3 | ----------------------- 4 | This example shows how to make Slope Graph. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_line().encode( 13 | x='year:O', 14 | y='median(yield)', 15 | color='site' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/sorted_error_bars_with_ci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sorted Error Bars showing Confidence Interval 3 | ============================================= 4 | This example shows how to show error bars using confidence intervals, while also sorting the y-axis based on x-axis values. 5 | """ 6 | # category: other charts 7 | 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.barley() 12 | 13 | points = alt.Chart(source).mark_point( 14 | filled=True, 15 | color='black' 16 | ).encode( 17 | x=alt.X('mean(yield)', title='Barley Yield'), 18 | y=alt.Y( 19 | 'variety', 20 | sort=alt.EncodingSortField( 21 | field='yield', 22 | op='mean', 23 | order='descending' 24 | ) 25 | ) 26 | ).properties( 27 | width=400, 28 | height=250 29 | ) 30 | 31 | error_bars = points.mark_rule().encode( 32 | x='ci0(yield)', 33 | x2='ci1(yield)', 34 | ) 35 | 36 | points + error_bars 37 | -------------------------------------------------------------------------------- /altair/examples/stacked_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stacked Bar Chart 3 | ----------------- 4 | 5 | This is an example of a stacked bar chart using data which contains crop yields over different regions and different years in the 1930s. 6 | """ 7 | # category: bar charts 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.barley() 12 | 13 | alt.Chart(source).mark_bar().encode( 14 | x='variety', 15 | y='sum(yield)', 16 | color='site' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/stacked_bar_chart_sorted_segments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stacked Bar Chart with Sorted Segments 3 | -------------------------------------- 4 | This is an example of a stacked-bar chart with the segments of each bar resorted. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | x='sum(yield)', 14 | y='variety', 15 | color='site', 16 | order=alt.Order( 17 | # Sort the segments of the bars by this field 18 | 'site', 19 | sort='ascending' 20 | ) 21 | ) 22 | -------------------------------------------------------------------------------- /altair/examples/stacked_bar_chart_with_text.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stacked Bar Chart with Text Overlay 3 | =================================== 4 | This example shows how to overlay text on a stacked bar chart. For both the 5 | bar and text marks, we use the ``stack`` argument in the ``x`` encoding to 6 | cause the values to be stacked horizontally. 7 | """ 8 | # category: bar charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source=data.barley() 13 | 14 | bars = alt.Chart(source).mark_bar().encode( 15 | x=alt.X('sum(yield):Q', stack='zero'), 16 | y=alt.Y('variety:N'), 17 | color=alt.Color('site') 18 | ) 19 | 20 | text = alt.Chart(source).mark_text(dx=-15, dy=3, color='white').encode( 21 | x=alt.X('sum(yield):Q', stack='zero'), 22 | y=alt.Y('variety:N'), 23 | detail='site:N', 24 | text=alt.Text('sum(yield):Q', format='.1f') 25 | ) 26 | 27 | bars + text 28 | -------------------------------------------------------------------------------- /altair/examples/stem_and_leaf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stem and Leaf Plot 3 | ------------------ 4 | This example shows how to make a stem and leaf plot. 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | import pandas as pd 9 | import numpy as np 10 | np.random.seed(42) 11 | 12 | # Generating random data 13 | source = pd.DataFrame({'samples': np.random.normal(50, 15, 100).astype(int).astype(str)}) 14 | 15 | # Splitting stem and leaf 16 | source['stem'] = source['samples'].str[:-1] 17 | source['leaf'] = source['samples'].str[-1] 18 | 19 | source = source.sort_values(by=['stem', 'leaf']) 20 | 21 | # Determining leaf position 22 | source['position'] = source.groupby('stem').cumcount().add(1) 23 | 24 | # Creating stem and leaf plot 25 | alt.Chart(source).mark_text( 26 | align='left', 27 | baseline='middle', 28 | dx=-5 29 | ).encode( 30 | alt.X('position:Q', title='', 31 | axis=alt.Axis(ticks=False, labels=False, grid=False) 32 | ), 33 | alt.Y('stem:N', title='', axis=alt.Axis(tickSize=0)), 34 | text='leaf:N', 35 | ).configure_axis( 36 | labelFontSize=20 37 | ).configure_text( 38 | fontSize=20 39 | ) 40 | -------------------------------------------------------------------------------- /altair/examples/step_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Step Chart 3 | ---------- 4 | This example shows Google's stock price over time. 5 | This uses the "step-after" interpolation scheme. 6 | The full list of interpolation options includes 'linear', 7 | 'linear-closed', 'step', 'step-before', 'step-after', 'basis', 8 | 'basis-open', 'basis-closed', 'cardinal', 'cardinal-open', 9 | 'cardinal-closed', 'bundle', and 'monotone'. 10 | """ 11 | # category: line charts 12 | import altair as alt 13 | from vega_datasets import data 14 | 15 | source = data.stocks() 16 | 17 | alt.Chart(source).mark_line(interpolate='step-after').encode( 18 | x='date', 19 | y='price' 20 | ).transform_filter( 21 | alt.datum.symbol == 'GOOG' 22 | ) 23 | -------------------------------------------------------------------------------- /altair/examples/streamgraph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Streamgraph 3 | ----------------- 4 | This example shows the streamgraph from vega-lite examples. 5 | """ 6 | # category: area charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.unemployment_across_industries.url 11 | 12 | alt.Chart(source).mark_area().encode( 13 | alt.X('yearmonth(date):T', 14 | axis=alt.Axis(format='%Y', domain=False, tickSize=0) 15 | ), 16 | alt.Y('sum(count):Q', stack='center', axis=None), 17 | alt.Color('series:N', 18 | scale=alt.Scale(scheme='category20b') 19 | ) 20 | ).interactive() 21 | -------------------------------------------------------------------------------- /altair/examples/strip_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple Strip Plot 3 | ----------------- 4 | A simple example of how to make a strip plot. 5 | """ 6 | # category: simple charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.cars() 11 | 12 | alt.Chart(source).mark_tick().encode( 13 | x='Horsepower:Q', 14 | y='Cylinders:O' 15 | ) 16 | -------------------------------------------------------------------------------- /altair/examples/stripplot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stripplot 3 | --------- 4 | This example shows how to make a Stripplot. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.movies.url 11 | 12 | stripplot = alt.Chart(source, width=40).mark_circle(size=8).encode( 13 | x=alt.X( 14 | 'jitter:Q', 15 | title=None, 16 | axis=alt.Axis(values=[0], ticks=True, grid=False, labels=False), 17 | scale=alt.Scale(), 18 | ), 19 | y=alt.Y('IMDB_Rating:Q'), 20 | color=alt.Color('Major_Genre:N', legend=None), 21 | column=alt.Column( 22 | 'Major_Genre:N', 23 | header=alt.Header( 24 | labelAngle=-90, 25 | titleOrient='top', 26 | labelOrient='bottom', 27 | labelAlign='right', 28 | labelPadding=3, 29 | ), 30 | ), 31 | ).transform_calculate( 32 | # Generate Gaussian jitter with a Box-Muller transform 33 | jitter='sqrt(-2*log(random()))*cos(2*PI*random())' 34 | ).configure_facet( 35 | spacing=0 36 | ).configure_view( 37 | stroke=None 38 | ) 39 | 40 | stripplot 41 | -------------------------------------------------------------------------------- /altair/examples/table_bubble_plot_github.py: -------------------------------------------------------------------------------- 1 | """ 2 | Table Bubble Plot (Github Punch Card) 3 | ------------------------------------- 4 | This example shows github contributions by the day of week and hour of the day. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.github.url 11 | 12 | alt.Chart(source).mark_circle().encode( 13 | x='hours(time):O', 14 | y='day(time):O', 15 | size='sum(count):Q' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakevdp/altair/19ec75714f12da19341bb3de46dcc67b90d89559/altair/examples/tests/__init__.py -------------------------------------------------------------------------------- /altair/examples/tests/test_examples.py: -------------------------------------------------------------------------------- 1 | import io 2 | import pkgutil 3 | 4 | import pytest 5 | 6 | from altair.utils.execeval import eval_block 7 | from altair import examples 8 | 9 | 10 | @pytest.fixture 11 | def require_altair_saver_png(): 12 | try: 13 | import altair_saver # noqa: F401 14 | except ImportError: 15 | pytest.skip("altair_saver not importable; cannot run saver tests") 16 | if "png" not in altair_saver.available_formats('vega-lite'): 17 | pytest.skip("altair_saver not configured to save to png") 18 | 19 | 20 | def iter_example_filenames(): 21 | for importer, modname, ispkg in pkgutil.iter_modules(examples.__path__): 22 | if ispkg or modname.startswith('_'): 23 | continue 24 | yield modname + '.py' 25 | 26 | 27 | @pytest.mark.parametrize('filename', iter_example_filenames()) 28 | def test_examples(filename: str): 29 | source = pkgutil.get_data(examples.__name__, filename) 30 | chart = eval_block(source) 31 | 32 | if chart is None: 33 | raise ValueError("Example file should define chart in its final " 34 | "statement.") 35 | chart.to_dict() 36 | 37 | 38 | @pytest.mark.parametrize('filename', iter_example_filenames()) 39 | def test_render_examples_to_png(require_altair_saver_png, filename): 40 | source = pkgutil.get_data(examples.__name__, filename) 41 | chart = eval_block(source) 42 | out = io.BytesIO() 43 | chart.save(out, format="png") 44 | assert out.getvalue().startswith(b'\x89PNG') 45 | -------------------------------------------------------------------------------- /altair/examples/top_k_items.py: -------------------------------------------------------------------------------- 1 | """ 2 | Top K Items 3 | ----------- 4 | This example shows how to use the window and transformation filter to display 5 | the Top items of a long list of items in decreasing order. 6 | Here we sort the top 10 highest ranking movies of IMDB. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.movies.url 13 | 14 | # Top 10 movies by IMBD rating 15 | alt.Chart( 16 | source, 17 | ).mark_bar().encode( 18 | x=alt.X('Title:N', sort='-y'), 19 | y=alt.Y('IMDB_Rating:Q'), 20 | color=alt.Color('IMDB_Rating:Q') 21 | 22 | ).transform_window( 23 | rank='rank(IMDB_Rating)', 24 | sort=[alt.SortField('IMDB_Rating', order='descending')] 25 | ).transform_filter( 26 | (alt.datum.rank < 10) 27 | ) -------------------------------------------------------------------------------- /altair/examples/top_k_letters.py: -------------------------------------------------------------------------------- 1 | """ 2 | Top K Letters 3 | ------------- 4 | This example shows how to use a window transform in order to display only the 5 | top K categories by number of entries. In this case, we rank the characters in 6 | the first paragraph of Dickens' *A Tale of Two Cities* by number of occurances. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | import pandas as pd 11 | import numpy as np 12 | 13 | # Excerpt from A Tale of Two Cities; public domain text 14 | text = """ 15 | It was the best of times, it was the worst of times, it was the age of wisdom, 16 | it was the age of foolishness, it was the epoch of belief, it was the epoch of 17 | incredulity, it was the season of Light, it was the season of Darkness, it was 18 | the spring of hope, it was the winter of despair, we had everything before us, 19 | we had nothing before us, we were all going direct to Heaven, we were all going 20 | direct the other way - in short, the period was so far like the present period, 21 | that some of its noisiest authorities insisted on its being received, for good 22 | or for evil, in the superlative degree of comparison only. 23 | """ 24 | 25 | source = pd.DataFrame( 26 | {'letters': np.array([c for c in text if c.isalpha()])} 27 | ) 28 | 29 | alt.Chart(source).transform_aggregate( 30 | count='count()', 31 | groupby=['letters'] 32 | ).transform_window( 33 | rank='rank(count)', 34 | sort=[alt.SortField('count', order='descending')] 35 | ).transform_filter( 36 | alt.datum.rank < 10 37 | ).mark_bar().encode( 38 | y=alt.Y('letters:N', sort='-x'), 39 | x='count:Q', 40 | ) 41 | -------------------------------------------------------------------------------- /altair/examples/top_k_with_others.py: -------------------------------------------------------------------------------- 1 | """ 2 | Top-K plot with Others 3 | ---------------------- 4 | This example shows how to use aggregate, window, and calculate transfromations 5 | to display the top-k directors by average worldwide gross while grouping the 6 | remaining directors as 'All Others'. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.movies.url 13 | 14 | alt.Chart(source).mark_bar().encode( 15 | x=alt.X("aggregate_gross:Q", aggregate="mean", title=None), 16 | y=alt.Y( 17 | "ranked_director:N", 18 | sort=alt.Sort(op="mean", field="aggregate_gross", order="descending"), 19 | title=None, 20 | ), 21 | ).transform_aggregate( 22 | aggregate_gross='mean(Worldwide_Gross)', 23 | groupby=["Director"], 24 | ).transform_window( 25 | rank='row_number()', 26 | sort=[alt.SortField("aggregate_gross", order="descending")], 27 | ).transform_calculate( 28 | ranked_director="datum.rank < 10 ? datum.Director : 'All Others'" 29 | ).properties( 30 | title="Top Directors by Average Worldwide Gross", 31 | ) 32 | -------------------------------------------------------------------------------- /altair/examples/trail_marker.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line Chart with Varying Size 3 | ---------------------------- 4 | This is example of using the ``trail`` marker to vary the size of a line. 5 | """ 6 | # category: line charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.wheat() 11 | 12 | alt.Chart(source).mark_trail().encode( 13 | x='year:T', 14 | y='wheat:Q', 15 | size='wheat:Q' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/trellis_area.py: -------------------------------------------------------------------------------- 1 | """ 2 | Trellis Area Chart 3 | ------------------ 4 | This example shows small multiples of an area chart. 5 | """ 6 | # category: area charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.iowa_electricity() 11 | 12 | alt.Chart(source).mark_area().encode( 13 | x="year:T", 14 | y="net_generation:Q", 15 | color="source:N", 16 | row="source:N" 17 | ).properties( 18 | height=100 19 | ) 20 | -------------------------------------------------------------------------------- /altair/examples/trellis_area_sort_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Trellis Area Sort Chart 3 | ----------------------- 4 | This example shows small multiples of an area chart. 5 | Stock prices of four large companies 6 | sorted by `['MSFT', 'AAPL', 'IBM', 'AMZN']` 7 | ''' 8 | # category: area charts 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.stocks() 13 | 14 | alt.Chart(source).transform_filter( 15 | alt.datum.symbol != 'GOOG' 16 | ).mark_area().encode( 17 | x='date:T', 18 | y='price:Q', 19 | color='symbol:N', 20 | row=alt.Row('symbol:N', sort=['MSFT', 'AAPL', 'IBM', 'AMZN']) 21 | ).properties(height=50, width=400) 22 | -------------------------------------------------------------------------------- /altair/examples/trellis_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Trellis Histogram 3 | ----------------- 4 | This example shows how to make a basic trellis histogram. 5 | https://vega.github.io/vega-lite/examples/trellis_bar_histogram.html 6 | """ 7 | # category: histograms 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.cars() 12 | 13 | alt.Chart(source).mark_bar().encode( 14 | alt.X("Horsepower:Q", bin=True), 15 | y='count()', 16 | row='Origin' 17 | ) 18 | -------------------------------------------------------------------------------- /altair/examples/trellis_scatter_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Trellis Scatter Plot 3 | ----------------------- 4 | This example shows how to make a trellis scatter plot. 5 | """ 6 | # category: scatter plots 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.cars() 11 | 12 | alt.Chart(source).mark_point().encode( 13 | x='Horsepower:Q', 14 | y='Miles_per_Gallon:Q', 15 | row='Origin:N' 16 | ) 17 | -------------------------------------------------------------------------------- /altair/examples/trellis_stacked_bar_chart.py: -------------------------------------------------------------------------------- 1 | """ 2 | Trellis Stacked Bar Chart 3 | ========================= 4 | This is an example of a horizontal stacked bar chart using data which contains crop yields over different regions and different years in the 1930s. 5 | """ 6 | # category: bar charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | source = data.barley() 11 | 12 | alt.Chart(source).mark_bar().encode( 13 | column='year', 14 | x='yield', 15 | y='variety', 16 | color='site' 17 | ).properties(width=220) 18 | -------------------------------------------------------------------------------- /altair/examples/us_employment.py: -------------------------------------------------------------------------------- 1 | """ 2 | The U.S. employment crash during the Great Recession 3 | ---------------------------------------------------- 4 | This example is a fully developed bar chart with negative values using the sample dataset of U.S. employment changes during the Great Recession. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | import pandas as pd 9 | from vega_datasets import data 10 | 11 | source = data.us_employment() 12 | presidents = pd.DataFrame([ 13 | { 14 | "start": "2006-01-01", 15 | "end": "2009-01-19", 16 | "president": "Bush" 17 | }, 18 | { 19 | "start": "2009-01-20", 20 | "end": "2015-12-31", 21 | "president": "Obama" 22 | } 23 | ]) 24 | 25 | bars = alt.Chart( 26 | source, 27 | title="The U.S. employment crash during the Great Recession" 28 | ).mark_bar().encode( 29 | x=alt.X("month:T", title=""), 30 | y=alt.Y("nonfarm_change:Q", title="Change in non-farm employment (in thousands)"), 31 | color=alt.condition( 32 | alt.datum.nonfarm_change > 0, 33 | alt.value("steelblue"), 34 | alt.value("orange") 35 | ) 36 | ) 37 | 38 | rule = alt.Chart(presidents).mark_rule( 39 | color="black", 40 | strokeWidth=2 41 | ).encode( 42 | x='end:T' 43 | ).transform_filter(alt.datum.president == "Bush") 44 | 45 | text = alt.Chart(presidents).mark_text( 46 | align='left', 47 | baseline='middle', 48 | dx=7, 49 | dy=-135, 50 | size=11 51 | ).encode( 52 | x='start:T', 53 | x2='end:T', 54 | text='president', 55 | color=alt.value('#000000') 56 | ) 57 | 58 | (bars + rule + text).properties(width=600) 59 | -------------------------------------------------------------------------------- /altair/examples/us_incomebrackets_by_state_facet.py: -------------------------------------------------------------------------------- 1 | """ 2 | US Income by State: Wrapped Facet 3 | --------------------------------- 4 | This example shows how to create a map of income in the US by state, 5 | faceted over income brackets 6 | """ 7 | # category: maps 8 | 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | states = alt.topo_feature(data.us_10m.url, 'states') 13 | source = data.income.url 14 | 15 | alt.Chart(source).mark_geoshape().encode( 16 | shape='geo:G', 17 | color='pct:Q', 18 | tooltip=['name:N', 'pct:Q'], 19 | facet=alt.Facet('group:N', columns=2), 20 | ).transform_lookup( 21 | lookup='id', 22 | from_=alt.LookupData(data=states, key='id'), 23 | as_='geo' 24 | ).properties( 25 | width=300, 26 | height=175, 27 | ).project( 28 | type='albersUsa' 29 | ) -------------------------------------------------------------------------------- /altair/examples/us_population_over_time.py: -------------------------------------------------------------------------------- 1 | """ 2 | US Population Over Time 3 | ======================= 4 | This chart visualizes the age distribution of the US population over time. 5 | It uses a slider widget that is bound to the year to visualize the age 6 | distribution over time. 7 | """ 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.population.url 13 | 14 | pink_blue = alt.Scale(domain=('Male', 'Female'), 15 | range=["steelblue", "salmon"]) 16 | 17 | slider = alt.binding_range(min=1900, max=2000, step=10) 18 | select_year = alt.selection_single(name="year", fields=['year'], 19 | bind=slider, init={'year': 2000}) 20 | 21 | alt.Chart(source).mark_bar().encode( 22 | x=alt.X('sex:N', title=None), 23 | y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))), 24 | color=alt.Color('sex:N', scale=pink_blue), 25 | column='age:O' 26 | ).properties( 27 | width=20 28 | ).add_selection( 29 | select_year 30 | ).transform_calculate( 31 | "sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female") 32 | ).transform_filter( 33 | select_year 34 | ).configure_facet( 35 | spacing=8 36 | ) 37 | -------------------------------------------------------------------------------- /altair/examples/us_population_over_time_facet.py: -------------------------------------------------------------------------------- 1 | """ 2 | US Population: Wrapped Facet 3 | ============================ 4 | This chart visualizes the age distribution of the US population over time, 5 | using a wrapped faceting of the data by decade. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | source = data.population.url 12 | 13 | alt.Chart(source).mark_area().encode( 14 | x='age:O', 15 | y=alt.Y( 16 | 'sum(people):Q', 17 | title='Population', 18 | axis=alt.Axis(format='~s') 19 | ), 20 | facet=alt.Facet('year:O', columns=5), 21 | ).properties( 22 | title='US Age Distribution By Year', 23 | width=90, 24 | height=80 25 | ) -------------------------------------------------------------------------------- /altair/examples/us_population_pyramid_over_time.py: -------------------------------------------------------------------------------- 1 | ''' 2 | US Population Pyramid Over Time 3 | =============================== 4 | A population pyramid shows the distribution of age groups within a population. 5 | It uses a slider widget that is bound to the year to visualize the age 6 | distribution over time. 7 | ''' 8 | # category: case studies 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = data.population.url 13 | 14 | slider = alt.binding_range(min=1850, max=2000, step=10) 15 | select_year = alt.selection_single(name='year', fields=['year'], 16 | bind=slider, init={'year': 2000}) 17 | 18 | base = alt.Chart(source).add_selection( 19 | select_year 20 | ).transform_filter( 21 | select_year 22 | ).transform_calculate( 23 | gender=alt.expr.if_(alt.datum.sex == 1, 'Male', 'Female') 24 | ).properties( 25 | width=250 26 | ) 27 | 28 | 29 | color_scale = alt.Scale(domain=['Male', 'Female'], 30 | range=['#1f77b4', '#e377c2']) 31 | 32 | left = base.transform_filter( 33 | alt.datum.gender == 'Female' 34 | ).encode( 35 | y=alt.Y('age:O', axis=None), 36 | x=alt.X('sum(people):Q', 37 | title='population', 38 | sort=alt.SortOrder('descending')), 39 | color=alt.Color('gender:N', scale=color_scale, legend=None) 40 | ).mark_bar().properties(title='Female') 41 | 42 | middle = base.encode( 43 | y=alt.Y('age:O', axis=None), 44 | text=alt.Text('age:Q'), 45 | ).mark_text().properties(width=20) 46 | 47 | right = base.transform_filter( 48 | alt.datum.gender == 'Male' 49 | ).encode( 50 | y=alt.Y('age:O', axis=None), 51 | x=alt.X('sum(people):Q', title='population'), 52 | color=alt.Color('gender:N', scale=color_scale, legend=None) 53 | ).mark_bar().properties(title='Male') 54 | 55 | alt.concat(left, middle, right, spacing=5) -------------------------------------------------------------------------------- /altair/examples/us_state_capitals.py: -------------------------------------------------------------------------------- 1 | """ 2 | U.S. state capitals overlayed on a map of the U.S 3 | ------------------------------------------------- 4 | This is a layered geographic visualization that shows US capitals 5 | overlayed on a map. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | from vega_datasets import data 10 | 11 | states = alt.topo_feature(data.us_10m.url, 'states') 12 | capitals = data.us_state_capitals.url 13 | 14 | # US states background 15 | background = alt.Chart(states).mark_geoshape( 16 | fill='lightgray', 17 | stroke='white' 18 | ).properties( 19 | title='US State Capitols', 20 | width=650, 21 | height=400 22 | ).project('albersUsa') 23 | 24 | # Points and text 25 | hover = alt.selection(type='single', on='mouseover', nearest=True, 26 | fields=['lat', 'lon']) 27 | 28 | base = alt.Chart(capitals).encode( 29 | longitude='lon:Q', 30 | latitude='lat:Q', 31 | ) 32 | 33 | text = base.mark_text(dy=-5, align='right').encode( 34 | alt.Text('city', type='nominal'), 35 | opacity=alt.condition(~hover, alt.value(0), alt.value(1)) 36 | ) 37 | 38 | points = base.mark_point().encode( 39 | color=alt.value('black'), 40 | size=alt.condition(~hover, alt.value(30), alt.value(100)) 41 | ).add_selection(hover) 42 | 43 | background + points + text 44 | -------------------------------------------------------------------------------- /altair/examples/violin_plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Violin Plot 3 | ----------- 4 | This example shows how to make a Violin Plot using Altair's density transform. 5 | """ 6 | # category: other charts 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | alt.Chart(data.cars()).transform_density( 11 | 'Miles_per_Gallon', 12 | as_=['Miles_per_Gallon', 'density'], 13 | extent=[5, 50], 14 | groupby=['Origin'] 15 | ).mark_area(orient='horizontal').encode( 16 | y='Miles_per_Gallon:Q', 17 | color='Origin:N', 18 | x=alt.X( 19 | 'density:Q', 20 | stack='center', 21 | impute=None, 22 | title=None, 23 | axis=alt.Axis(labels=False, values=[0],grid=False, ticks=True), 24 | ), 25 | column=alt.Column( 26 | 'Origin:N', 27 | header=alt.Header( 28 | titleOrient='bottom', 29 | labelOrient='bottom', 30 | labelPadding=0, 31 | ), 32 | ) 33 | ).properties( 34 | width=100 35 | ).configure_facet( 36 | spacing=0 37 | ).configure_view( 38 | stroke=None 39 | ) 40 | -------------------------------------------------------------------------------- /altair/examples/weather_heatmap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Seattle Weather Heatmap 3 | ----------------------- 4 | This example shows the 2010 daily high temperature (F) in Seattle, WA. 5 | """ 6 | # category: case studies 7 | import altair as alt 8 | from vega_datasets import data 9 | 10 | # Since the data is more than 5,000 rows we'll import it from a URL 11 | source = data.seattle_temps.url 12 | 13 | alt.Chart( 14 | source, 15 | title="2010 Daily High Temperature (F) in Seattle, WA" 16 | ).mark_rect().encode( 17 | x='date(date):O', 18 | y='month(date):O', 19 | color=alt.Color('max(temp):Q', scale=alt.Scale(scheme="inferno")), 20 | tooltip=[ 21 | alt.Tooltip('monthdate(date):T', title='Date'), 22 | alt.Tooltip('max(temp):Q', title='Max Temp') 23 | ] 24 | ).properties(width=550) 25 | -------------------------------------------------------------------------------- /altair/examples/wheat_wages.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wheat and Wages 3 | --------------- 4 | A recreation of William Playfair's classic chart visualizing 5 | the price of wheat, the wages of a mechanic, and the reigning British monarch. 6 | 7 | This is a more polished version of the simpler chart in :ref:`gallery_bar_and_line_with_dual_axis`. 8 | """ 9 | # category: case studies 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | 14 | base_wheat = alt.Chart(data.wheat.url).transform_calculate( 15 | year_end="+datum.year + 5") 16 | 17 | base_monarchs = alt.Chart(data.monarchs.url).transform_calculate( 18 | offset="((!datum.commonwealth && datum.index % 2) ? -1: 1) * 2 + 95", 19 | off2="((!datum.commonwealth && datum.index % 2) ? -1: 1) + 95", 20 | y="95", 21 | x="+datum.start + (+datum.end - +datum.start)/2" 22 | ) 23 | 24 | bars = base_wheat.mark_bar(**{"fill": "#aaa", "stroke": "#999"}).encode( 25 | x=alt.X("year:Q", axis=alt.Axis(format='d', tickCount=5)), 26 | y=alt.Y("wheat:Q", axis=alt.Axis(zindex=1)), 27 | x2=alt.X2("year_end") 28 | ) 29 | 30 | area = base_wheat.mark_area(**{"color": "#a4cedb", "opacity": 0.7}).encode( 31 | x=alt.X("year:Q"), 32 | y=alt.Y("wages:Q") 33 | ) 34 | 35 | area_line_1 = area.mark_line(**{"color": "#000", "opacity": 0.7}) 36 | area_line_2 = area.mark_line(**{"yOffset": -2, "color": "#EE8182"}) 37 | 38 | top_bars = base_monarchs.mark_bar(stroke="#000").encode( 39 | x=alt.X("start:Q"), 40 | x2=alt.X2("end"), 41 | y=alt.Y("y:Q"), 42 | y2=alt.Y2("offset"), 43 | fill=alt.Fill("commonwealth:N", legend=None, scale=alt.Scale(range=["black", "white"])) 44 | ) 45 | 46 | top_text = base_monarchs.mark_text(**{"yOffset": 14, "fontSize": 9, "fontStyle": "italic"}).encode( 47 | x=alt.X("x:Q"), 48 | y=alt.Y("off2:Q"), 49 | text=alt.Text("name:N") 50 | ) 51 | 52 | (bars + area + area_line_1 + area_line_2 + top_bars + top_text).properties( 53 | width=900, height=400 54 | ).configure_axis( 55 | title=None, gridColor="white", gridOpacity=0.25, domain=False 56 | ).configure_view( 57 | stroke="transparent" 58 | ) -------------------------------------------------------------------------------- /altair/examples/wilkinson-dot-plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wilkinson Dot Plot 3 | ------------------ 4 | An example of a `Wilkinson Dot Plot `_ 5 | """ 6 | # category: other charts 7 | 8 | import altair as alt 9 | import pandas as pd 10 | 11 | source = pd.DataFrame( 12 | {"data":[1,1,1,1,1,1,1,1,1,1, 13 | 2,2,2, 14 | 3,3, 15 | 4,4,4,4,4,4] 16 | } 17 | ) 18 | 19 | alt.Chart(source).mark_circle(opacity=1).transform_window( 20 | id='rank()', 21 | groupby=['data'] 22 | ).encode( 23 | alt.X('data:O'), 24 | alt.Y('id:O', 25 | axis=None, 26 | sort='descending') 27 | ).properties(height=100) 28 | -------------------------------------------------------------------------------- /altair/examples/wind_vector_map.py: -------------------------------------------------------------------------------- 1 | """ 2 | Wind Vector Map 3 | --------------- 4 | An example showing a vector array map showing wind speed and direction using ``wedge`` 5 | as shape for ``mark_point`` and ``angle`` encoding for the wind direction. 6 | This is adapted from this corresponding Vega-Lite Example: 7 | `Wind Vector Map `_. 8 | """ 9 | # category: scatter plots 10 | 11 | import altair as alt 12 | from vega_datasets import data 13 | 14 | source = data.windvectors() 15 | 16 | alt.Chart(source).mark_point(shape="wedge", filled=True).encode( 17 | latitude="latitude", 18 | longitude="longitude", 19 | color=alt.Color( 20 | "dir", scale=alt.Scale(domain=[0, 360], scheme="rainbow"), legend=None 21 | ), 22 | angle=alt.Angle("dir", scale=alt.Scale(domain=[0, 360], range=[180, 540])), 23 | size=alt.Size("speed", scale=alt.Scale(rangeMax=500)), 24 | ).project("equalEarth") 25 | -------------------------------------------------------------------------------- /altair/examples/window_rank.py: -------------------------------------------------------------------------------- 1 | """ 2 | Window Rank Line Chart 3 | ---------------------- 4 | This example shows the Group F rankings in the 2018 World Cup after each matchday. 5 | A window transformation is used to rank each after each match day, sorting by points and difference. 6 | """ 7 | # category: case studies 8 | import altair as alt 9 | import pandas as pd 10 | 11 | source = pd.DataFrame( 12 | [ 13 | {"team": "Germany", "matchday": 1, "point": 0, "diff": -1}, 14 | {"team": "Germany", "matchday": 2, "point": 3, "diff": 0}, 15 | {"team": "Germany", "matchday": 3, "point": 3, "diff": -2}, 16 | {"team": "Mexico", "matchday": 1, "point": 3, "diff": 1}, 17 | {"team": "Mexico", "matchday": 2, "point": 6, "diff": 2}, 18 | {"team": "Mexico", "matchday": 3, "point": 6, "diff": -1}, 19 | {"team": "South Korea", "matchday": 1, "point": 0, "diff": -1}, 20 | {"team": "South Korea", "matchday": 2, "point": 0, "diff": -2}, 21 | {"team": "South Korea", "matchday": 3, "point": 3, "diff": 0}, 22 | {"team": "Sweden", "matchday": 1, "point": 3, "diff": 1}, 23 | {"team": "Sweden", "matchday": 2, "point": 3, "diff": 0}, 24 | {"team": "Sweden", "matchday": 3, "point": 6, "diff": 3}, 25 | ] 26 | ) 27 | 28 | color_scale = alt.Scale( 29 | domain=["Germany", "Mexico", "South Korea", "Sweden"], 30 | range=["#000000", "#127153", "#C91A3C", "#0C71AB"], 31 | ) 32 | 33 | alt.Chart(source).mark_line().encode( 34 | x="matchday:O", y="rank:O", color=alt.Color("team:N", scale=color_scale) 35 | ).transform_window( 36 | rank="rank()", 37 | sort=[ 38 | alt.SortField("point", order="descending"), 39 | alt.SortField("diff", order="descending"), 40 | ], 41 | groupby=["matchday"], 42 | ).properties(title="World Cup 2018: Group F Rankings") 43 | -------------------------------------------------------------------------------- /altair/examples/world_map.py: -------------------------------------------------------------------------------- 1 | """ 2 | World Map 3 | --------- 4 | 5 | This example shows how to create a world map using data generators for 6 | different background layers. 7 | """ 8 | # category: maps 9 | 10 | import altair as alt 11 | from vega_datasets import data 12 | 13 | # Data generators for the background 14 | sphere = alt.sphere() 15 | graticule = alt.graticule() 16 | 17 | # Source of land data 18 | source = alt.topo_feature(data.world_110m.url, 'countries') 19 | 20 | # Layering and configuring the components 21 | alt.layer( 22 | alt.Chart(sphere).mark_geoshape(fill='lightblue'), 23 | alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5), 24 | alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black') 25 | ).project( 26 | 'naturalEarth1' 27 | ).properties(width=600, height=400).configure_view(stroke=None) 28 | -------------------------------------------------------------------------------- /altair/examples/world_projections.py: -------------------------------------------------------------------------------- 1 | """ 2 | World Projections 3 | ----------------- 4 | This example shows a map of the countries of the world using four available 5 | geographic projections. For more details on the projections available in 6 | Altair, see https://vega.github.io/vega-lite/docs/projection.html 7 | """ 8 | # category: maps 9 | import altair as alt 10 | from vega_datasets import data 11 | 12 | source = alt.topo_feature(data.world_110m.url, 'countries') 13 | 14 | base = alt.Chart(source).mark_geoshape( 15 | fill='#666666', 16 | stroke='white' 17 | ).properties( 18 | width=300, 19 | height=180 20 | ) 21 | 22 | projections = ['equirectangular', 'mercator', 'orthographic', 'gnomonic'] 23 | charts = [base.project(proj).properties(title=proj) 24 | for proj in projections] 25 | 26 | alt.concat(*charts, columns=2) 27 | -------------------------------------------------------------------------------- /altair/expr/__init__.py: -------------------------------------------------------------------------------- 1 | """Tools for creating transform & filter expressions with a python syntax""" 2 | # flake8: noqa 3 | from .core import datum, Expression 4 | from .funcs import * 5 | from .consts import * 6 | -------------------------------------------------------------------------------- /altair/expr/consts.py: -------------------------------------------------------------------------------- 1 | from .core import ConstExpression 2 | 3 | 4 | CONST_LISTING = { 5 | "NaN": "not a number (same as JavaScript literal NaN)", 6 | "LN10": "the natural log of 10 (alias to Math.LN10)", 7 | "E": "the transcendental number e (alias to Math.E)", 8 | "LOG10E": "the base 10 logarithm e (alias to Math.LOG10E)", 9 | "LOG2E": "the base 2 logarithm of e (alias to Math.LOG2E)", 10 | "SQRT1_2": "the square root of 0.5 (alias to Math.SQRT1_2)", 11 | "LN2": "the natural log of 2 (alias to Math.LN2)", 12 | "SQRT2": "the square root of 2 (alias to Math.SQRT1_2)", 13 | "PI": "the transcendental number pi (alias to Math.PI)", 14 | } 15 | 16 | NAME_MAP = {} 17 | 18 | 19 | def _populate_namespace(): 20 | globals_ = globals() 21 | for name, doc in CONST_LISTING.items(): 22 | py_name = NAME_MAP.get(name, name) 23 | globals_[py_name] = ConstExpression(name, doc) 24 | yield py_name 25 | 26 | 27 | __all__ = list(_populate_namespace()) 28 | -------------------------------------------------------------------------------- /altair/expr/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakevdp/altair/19ec75714f12da19341bb3de46dcc67b90d89559/altair/expr/tests/__init__.py -------------------------------------------------------------------------------- /altair/sphinxext/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakevdp/altair/19ec75714f12da19341bb3de46dcc67b90d89559/altair/sphinxext/__init__.py -------------------------------------------------------------------------------- /altair/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakevdp/altair/19ec75714f12da19341bb3de46dcc67b90d89559/altair/tests/__init__.py -------------------------------------------------------------------------------- /altair/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .core import ( 2 | infer_vegalite_type, 3 | infer_encoding_types, 4 | sanitize_dataframe, 5 | parse_shorthand, 6 | use_signature, 7 | update_subtraits, 8 | update_nested, 9 | display_traceback, 10 | SchemaBase, 11 | Undefined, 12 | ) 13 | from .html import spec_to_html 14 | from .plugin_registry import PluginRegistry 15 | from .deprecation import AltairDeprecationWarning 16 | 17 | 18 | __all__ = ( 19 | "infer_vegalite_type", 20 | "infer_encoding_types", 21 | "sanitize_dataframe", 22 | "spec_to_html", 23 | "parse_shorthand", 24 | "use_signature", 25 | "update_subtraits", 26 | "update_nested", 27 | "display_traceback", 28 | "AltairDeprecationWarning", 29 | "SchemaBase", 30 | "Undefined", 31 | "PluginRegistry", 32 | ) 33 | -------------------------------------------------------------------------------- /altair/utils/deprecation.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | import functools 3 | 4 | 5 | class AltairDeprecationWarning(UserWarning): 6 | pass 7 | 8 | 9 | def deprecated(message=None): 10 | """Decorator to deprecate a function or class. 11 | 12 | Parameters 13 | ---------- 14 | message : string (optional) 15 | The deprecation message 16 | """ 17 | 18 | def wrapper(obj): 19 | return _deprecate(obj, message=message) 20 | 21 | return wrapper 22 | 23 | 24 | def _deprecate(obj, name=None, message=None): 25 | """Return a version of a class or function that raises a deprecation warning. 26 | 27 | Parameters 28 | ---------- 29 | obj : class or function 30 | The object to create a deprecated version of. 31 | name : string (optional) 32 | The name of the deprecated object 33 | message : string (optional) 34 | The deprecation message 35 | 36 | Returns 37 | ------- 38 | deprecated_obj : 39 | The deprecated version of obj 40 | 41 | Examples 42 | -------- 43 | >>> class Foo(object): pass 44 | >>> OldFoo = _deprecate(Foo, "OldFoo") 45 | >>> f = OldFoo() # doctest: +SKIP 46 | AltairDeprecationWarning: alt.OldFoo is deprecated. Use alt.Foo instead. 47 | """ 48 | if message is None: 49 | message = "alt.{} is deprecated. Use alt.{} instead." "".format( 50 | name, obj.__name__ 51 | ) 52 | if isinstance(obj, type): 53 | return type( 54 | name, 55 | (obj,), 56 | { 57 | "__doc__": obj.__doc__, 58 | "__init__": _deprecate(obj.__init__, "__init__", message), 59 | }, 60 | ) 61 | elif callable(obj): 62 | 63 | @functools.wraps(obj) 64 | def new_obj(*args, **kwargs): 65 | warnings.warn(message, AltairDeprecationWarning) 66 | return obj(*args, **kwargs) 67 | 68 | return new_obj 69 | else: 70 | raise ValueError("Cannot deprecate object of type {}".format(type(obj))) 71 | -------------------------------------------------------------------------------- /altair/utils/execeval.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import sys 3 | 4 | 5 | if sys.version_info > (3, 8): 6 | Module = ast.Module 7 | else: 8 | # Mock the Python >= 3.8 API 9 | def Module(nodelist, type_ignores): 10 | return ast.Module(nodelist) 11 | 12 | 13 | class _CatchDisplay(object): 14 | """Class to temporarily catch sys.displayhook""" 15 | 16 | def __init__(self): 17 | self.output = None 18 | 19 | def __enter__(self): 20 | self.old_hook = sys.displayhook 21 | sys.displayhook = self 22 | return self 23 | 24 | def __exit__(self, type, value, traceback): 25 | sys.displayhook = self.old_hook 26 | # Returning False will cause exceptions to propagate 27 | return False 28 | 29 | def __call__(self, output): 30 | self.output = output 31 | 32 | 33 | def eval_block(code, namespace=None, filename=""): 34 | """ 35 | Execute a multi-line block of code in the given namespace 36 | 37 | If the final statement in the code is an expression, return 38 | the result of the expression. 39 | """ 40 | tree = ast.parse(code, filename="", mode="exec") 41 | if namespace is None: 42 | namespace = {} 43 | catch_display = _CatchDisplay() 44 | 45 | if isinstance(tree.body[-1], ast.Expr): 46 | to_exec, to_eval = tree.body[:-1], tree.body[-1:] 47 | else: 48 | to_exec, to_eval = tree.body, [] 49 | 50 | for node in to_exec: 51 | compiled = compile(Module([node], []), filename=filename, mode="exec") 52 | exec(compiled, namespace) 53 | 54 | with catch_display: 55 | for node in to_eval: 56 | compiled = compile( 57 | ast.Interactive([node]), filename=filename, mode="single" 58 | ) 59 | exec(compiled, namespace) 60 | 61 | return catch_display.output 62 | -------------------------------------------------------------------------------- /altair/utils/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakevdp/altair/19ec75714f12da19341bb3de46dcc67b90d89559/altair/utils/tests/__init__.py -------------------------------------------------------------------------------- /altair/utils/tests/test_deprecation.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | import altair as alt 4 | from altair.utils import AltairDeprecationWarning 5 | from altair.utils.deprecation import _deprecate, deprecated 6 | 7 | 8 | def test_deprecated_class(): 9 | OldChart = _deprecate(alt.Chart, "OldChart") 10 | with pytest.warns(AltairDeprecationWarning) as record: 11 | OldChart() 12 | assert "alt.OldChart" in record[0].message.args[0] 13 | assert "alt.Chart" in record[0].message.args[0] 14 | 15 | 16 | def test_deprecation_decorator(): 17 | @deprecated(message="func is deprecated") 18 | def func(x): 19 | return x + 1 20 | 21 | with pytest.warns(AltairDeprecationWarning) as record: 22 | y = func(1) 23 | assert y == 2 24 | assert record[0].message.args[0] == "func is deprecated" 25 | -------------------------------------------------------------------------------- /altair/utils/tests/test_execeval.py: -------------------------------------------------------------------------------- 1 | from ..execeval import eval_block 2 | 3 | HAS_RETURN = """ 4 | x = 4 5 | y = 2 * x 6 | 3 * y 7 | """ 8 | 9 | NO_RETURN = """ 10 | x = 4 11 | y = 2 * x 12 | z = 3 * y 13 | """ 14 | 15 | 16 | def test_eval_block_with_return(): 17 | _globals = {} 18 | result = eval_block(HAS_RETURN, _globals) 19 | assert result == 24 20 | assert _globals["x"] == 4 21 | assert _globals["y"] == 8 22 | 23 | 24 | def test_eval_block_without_return(): 25 | _globals = {} 26 | result = eval_block(NO_RETURN, _globals) 27 | assert result is None 28 | assert _globals["x"] == 4 29 | assert _globals["y"] == 8 30 | assert _globals["z"] == 24 31 | -------------------------------------------------------------------------------- /altair/utils/tests/test_html.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from ..html import spec_to_html 4 | 5 | 6 | @pytest.fixture 7 | def spec(): 8 | return { 9 | "data": {"url": "data.json"}, 10 | "mark": "point", 11 | "encoding": { 12 | "x": {"field": "x", "type": "quantitative"}, 13 | "y": {"field": "y", "type": "quantitative"}, 14 | }, 15 | } 16 | 17 | 18 | @pytest.mark.parametrize("requirejs", [True, False]) 19 | @pytest.mark.parametrize("fullhtml", [True, False]) 20 | def test_spec_to_html(requirejs, fullhtml, spec): 21 | # We can't test that the html actually renders, but we'll test aspects of 22 | # it to make certain that the keywords are respected. 23 | vegaembed_version = ("3.12",) 24 | vegalite_version = ("3.0",) 25 | vega_version = "4.0" 26 | 27 | html = spec_to_html( 28 | spec, 29 | mode="vega-lite", 30 | requirejs=requirejs, 31 | fullhtml=fullhtml, 32 | vegalite_version=vegalite_version, 33 | vegaembed_version=vegaembed_version, 34 | vega_version=vega_version, 35 | ) 36 | html = html.strip() 37 | 38 | if fullhtml: 39 | assert html.startswith("") 40 | assert html.endswith("") 41 | else: 42 | assert html.startswith("