├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug-report.yml
│ ├── config.yml
│ └── feature-request.yml
├── dependabot.yaml
├── pull_request_template.md
├── release.yml
└── workflows
│ ├── build.yml
│ ├── check-pr.yml
│ ├── docbuild.yml
│ └── lint.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── NOTES_FOR_MAINTAINERS.md
├── README.md
├── RELEASING.md
├── altair
├── __init__.py
├── _magics.py
├── expr
│ ├── __init__.py
│ ├── consts.py
│ ├── core.py
│ └── funcs.py
├── jupyter
│ ├── __init__.py
│ ├── js
│ │ ├── README.md
│ │ └── index.js
│ └── jupyter_chart.py
├── py.typed
├── theme.py
├── typing
│ └── __init__.py
├── utils
│ ├── __init__.py
│ ├── _dfi_types.py
│ ├── _importers.py
│ ├── _show.py
│ ├── _transformed_data.py
│ ├── _vegafusion_data.py
│ ├── compiler.py
│ ├── core.py
│ ├── data.py
│ ├── deprecation.py
│ ├── display.py
│ ├── execeval.py
│ ├── html.py
│ ├── mimebundle.py
│ ├── plugin_registry.py
│ ├── save.py
│ ├── schemapi.py
│ ├── selection.py
│ └── server.py
└── vegalite
│ ├── __init__.py
│ ├── api.py
│ ├── data.py
│ ├── display.py
│ ├── schema.py
│ └── v5
│ ├── __init__.py
│ ├── api.py
│ ├── compiler.py
│ ├── data.py
│ ├── display.py
│ ├── schema
│ ├── __init__.py
│ ├── _config.py
│ ├── _typing.py
│ ├── channels.py
│ ├── core.py
│ ├── mixins.py
│ ├── vega-lite-schema.json
│ └── vega-themes.json
│ └── theme.py
├── design
├── altair-logo-light.png
├── altair-logo-light.svg
├── altair-logo.png
└── altair-logo.svg
├── doc
├── .gitignore
├── _static
│ ├── altair-gallery.css
│ ├── altair-logo-light.png
│ ├── altair-plot.css
│ ├── chart.html
│ ├── custom.css
│ ├── favicon.ico
│ ├── gray-square.png
│ ├── jupyter_chart
│ │ ├── accessing_variable_params.mov
│ │ ├── index_selection_param.mov
│ │ ├── interval_selection_param.mov
│ │ ├── linking_interval_selection.mov
│ │ ├── linking_variable_params.mov
│ │ ├── linking_variable_params2.mov
│ │ ├── observing_variable_params.mov
│ │ ├── point_selection_param.mov
│ │ ├── setting_variable_params.mov
│ │ ├── simple_bar.svg
│ │ └── updating_charts.mov
│ ├── stocks_it-IT.svg
│ └── theme_overrides.css
├── _templates
│ ├── class.rst
│ ├── navbar-project.html
│ └── sidebar-logo.html
├── about
│ ├── citing.rst
│ ├── code_of_conduct.rst
│ ├── governance.rst
│ ├── roadmap.rst
│ └── versioning.rst
├── case_studies
│ ├── exploring-weather.rst
│ ├── index.rst
│ └── numpy-tooltip-images.rst
├── conf.py
├── getting_started
│ ├── getting_help.rst
│ ├── installation.rst
│ ├── overview.rst
│ ├── project_philosophy.rst
│ ├── resources.rst
│ └── starting.rst
├── index.rst
├── releases
│ └── changes.rst
└── user_guide
│ ├── api.rst
│ ├── compound_charts.rst
│ ├── configuration.rst
│ ├── custom_renderers.rst
│ ├── customization.rst
│ ├── data.rst
│ ├── data_transformers.rst
│ ├── display_frontends.rst
│ ├── encodings
│ ├── channel_options.rst
│ ├── channels.rst
│ └── index.rst
│ ├── interactions
│ ├── bindings_widgets.rst
│ ├── expressions.rst
│ ├── index.rst
│ ├── jupyter_chart.rst
│ └── parameters.rst
│ ├── internals.rst
│ ├── large_datasets.rst
│ ├── marks
│ ├── arc.rst
│ ├── area.rst
│ ├── bar.rst
│ ├── boxplot.rst
│ ├── circle.rst
│ ├── errorband.rst
│ ├── errorbar.rst
│ ├── geoshape.rst
│ ├── image.rst
│ ├── index.rst
│ ├── line.rst
│ ├── point.rst
│ ├── rect.rst
│ ├── rule.rst
│ ├── square.rst
│ ├── text.rst
│ ├── tick.rst
│ └── trail.rst
│ ├── saving_charts.rst
│ ├── scale_resolve.rst
│ ├── times_and_dates.rst
│ └── transform
│ ├── aggregate.rst
│ ├── bin.rst
│ ├── calculate.rst
│ ├── density.rst
│ ├── extent.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
├── images
├── cars.png
└── cars_scatter_bar.gif
├── paper
├── paper.bib
├── paper.md
└── seattle_weather_interactive.png
├── pyproject.toml
├── sphinxext
├── __init__.py
├── altairgallery.py
├── code_ref.py
├── schematable.py
└── utils.py
├── tests
├── __init__.py
├── altair_theme_test.py
├── examples_arguments_syntax
│ ├── __init__.py
│ ├── airport_connections.py
│ ├── annual_weather_heatmap.py
│ ├── anscombe_plot.py
│ ├── area_chart_gradient.py
│ ├── area_faceted.py
│ ├── bar_and_line_with_dual_axis.py
│ ├── bar_chart_faceted_compact.py
│ ├── bar_chart_horizontal.py
│ ├── bar_chart_sorted.py
│ ├── bar_chart_with_highlighted_bar.py
│ ├── bar_chart_with_highlighted_segment.py
│ ├── bar_chart_with_labels.py
│ ├── bar_chart_with_labels_measured_luminance.py
│ ├── bar_chart_with_mean_line.py
│ ├── bar_chart_with_negatives.py
│ ├── bar_chart_with_range.py
│ ├── bar_chart_with_single_threshold.py
│ ├── bar_faceted_stacked.py
│ ├── bar_rounded.py
│ ├── bar_with_rolling_mean.py
│ ├── beckers_barley_facet.py
│ ├── beckers_barley_wrapped_facet.py
│ ├── boxplot.py
│ ├── bubble_plot.py
│ ├── bump_chart.py
│ ├── calculate_residuals.py
│ ├── candlestick_chart.py
│ ├── choropleth.py
│ ├── choropleth_repeat.py
│ ├── co2_concentration.py
│ ├── comet_chart.py
│ ├── cumulative_count_chart.py
│ ├── dendrogram.py
│ ├── density_repeat.py
│ ├── density_stack.py
│ ├── deviation_ellipses.py
│ ├── distributions_and_medians_of_likert_scale_ratings.py
│ ├── distributions_faceted_histogram.py
│ ├── diverging_stacked_bar_chart.py
│ ├── donut_chart.py
│ ├── dot_dash_plot.py
│ ├── empirical_cumulative_distribution_function.py
│ ├── errorbars_with_ci.py
│ ├── errorbars_with_std.py
│ ├── falkensee.py
│ ├── filled_step_chart.py
│ ├── gantt_chart.py
│ ├── gapminder_bubble_plot.py
│ ├── groupby-map.py
│ ├── grouped_bar_chart.py
│ ├── grouped_bar_chart2.py
│ ├── grouped_bar_chart_horizontal.py
│ ├── grouped_bar_chart_overlapping_bars.py
│ ├── grouped_bar_chart_with_error_bars.py
│ ├── heat_lane.py
│ ├── hexbins.py
│ ├── histogram_gradient_color.py
│ ├── histogram_heatmap.py
│ ├── histogram_responsive.py
│ ├── histogram_scatterplot.py
│ ├── histogram_with_a_global_mean_overlay.py
│ ├── horizon_graph.py
│ ├── horizontal_stacked_bar_chart.py
│ ├── interactive_aggregation.py
│ ├── interactive_bar_select_highlight.py
│ ├── interactive_brush.py
│ ├── interactive_column_selection.py
│ ├── interactive_cross_highlight.py
│ ├── interactive_layered_crossfilter.py
│ ├── interactive_legend.py
│ ├── interactive_reorder_stacked_bars.py
│ ├── interactive_scatter_plot.py
│ ├── interval_selection.py
│ ├── interval_selection_map_quakes.py
│ ├── iowa_electricity.py
│ ├── isotype.py
│ ├── isotype_emoji.py
│ ├── isotype_grid.py
│ ├── lasagna_plot.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_arrows.py
│ ├── line_chart_with_color_datum.py
│ ├── line_chart_with_cumsum.py
│ ├── line_chart_with_cumsum_faceted.py
│ ├── line_chart_with_custom_legend.py
│ ├── line_chart_with_datum.py
│ ├── line_chart_with_generator.py
│ ├── line_chart_with_interpolation.py
│ ├── line_chart_with_points.py
│ ├── line_chart_with_points_stroked.py
│ ├── line_custom_order.py
│ ├── line_percent.py
│ ├── line_with_ci.py
│ ├── line_with_last_value_labeled.py
│ ├── line_with_log_scale.py
│ ├── london_tube.py
│ ├── mosaic_with_labels.py
│ ├── multi_series_line.py
│ ├── multifeature_scatter_plot.py
│ ├── multiline_highlight.py
│ ├── multiline_tooltip.py
│ ├── multiline_tooltip_standard.py
│ ├── multiple_interactions.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
│ ├── point_map.py
│ ├── polar_bar_chart.py
│ ├── poly_fit_regression.py
│ ├── pyramid.py
│ ├── radial_chart.py
│ ├── ranged_dot_plot.py
│ ├── ridgeline_plot.py
│ ├── scatter_faceted.py
│ ├── scatter_href.py
│ ├── scatter_linked_brush.py
│ ├── scatter_linked_table.py
│ ├── scatter_marginal_hist.py
│ ├── scatter_matrix.py
│ ├── scatter_point_paths_hover.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
│ ├── scatter_with_shaded_area.py
│ ├── seattle_weather_interactive.py
│ ├── select_detail.py
│ ├── select_mark_area.py
│ ├── selection_histogram.py
│ ├── selection_layer_bar_month.py
│ ├── selection_zorder.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
│ ├── strip_plot_jitter.py
│ ├── table_bubble_plot_github.py
│ ├── top_k_items.py
│ ├── top_k_letters.py
│ ├── top_k_with_others.py
│ ├── trail_marker.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
│ ├── waterfall_chart.py
│ ├── wheat_wages.py
│ ├── wilkinson-dot-plot.py
│ ├── wind_vector_map.py
│ ├── window_rank.py
│ ├── world_map.py
│ └── world_projections.py
├── examples_methods_syntax
│ ├── __init__.py
│ ├── airport_connections.py
│ ├── annual_weather_heatmap.py
│ ├── anscombe_plot.py
│ ├── area_faceted.py
│ ├── bar_chart_faceted_compact.py
│ ├── bar_chart_sorted.py
│ ├── bar_chart_with_labels_measured_luminance.py
│ ├── bar_chart_with_range.py
│ ├── bar_chart_with_single_threshold.py
│ ├── beckers_barley_facet.py
│ ├── beckers_barley_wrapped_facet.py
│ ├── bump_chart.py
│ ├── calculate_residuals.py
│ ├── candlestick_chart.py
│ ├── co2_concentration.py
│ ├── comet_chart.py
│ ├── cumulative_count_chart.py
│ ├── density_stack.py
│ ├── deviation_ellipses.py
│ ├── distributions_and_medians_of_likert_scale_ratings.py
│ ├── distributions_faceted_histogram.py
│ ├── diverging_stacked_bar_chart.py
│ ├── donut_chart.py
│ ├── errorbars_with_ci.py
│ ├── errorbars_with_std.py
│ ├── falkensee.py
│ ├── gapminder_bubble_plot.py
│ ├── groupby-map.py
│ ├── grouped_bar_chart2.py
│ ├── grouped_bar_chart_overlapping_bars.py
│ ├── grouped_bar_chart_with_error_bars.py
│ ├── heat_lane.py
│ ├── hexbins.py
│ ├── histogram_gradient_color.py
│ ├── histogram_heatmap.py
│ ├── histogram_responsive.py
│ ├── histogram_scatterplot.py
│ ├── histogram_with_a_global_mean_overlay.py
│ ├── horizon_graph.py
│ ├── interactive_aggregation.py
│ ├── interactive_bar_select_highlight.py
│ ├── interactive_column_selection.py
│ ├── interactive_cross_highlight.py
│ ├── interactive_layered_crossfilter.py
│ ├── interactive_legend.py
│ ├── interval_selection.py
│ ├── interval_selection_map_quakes.py
│ ├── iowa_electricity.py
│ ├── isotype.py
│ ├── isotype_emoji.py
│ ├── isotype_grid.py
│ ├── lasagna_plot.py
│ ├── layered_area_chart.py
│ ├── layered_bar_chart.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_cumsum_faceted.py
│ ├── line_chart_with_custom_legend.py
│ ├── line_custom_order.py
│ ├── line_percent.py
│ ├── line_with_ci.py
│ ├── line_with_last_value_labeled.py
│ ├── line_with_log_scale.py
│ ├── london_tube.py
│ ├── mosaic_with_labels.py
│ ├── multifeature_scatter_plot.py
│ ├── multiline_highlight.py
│ ├── multiline_tooltip.py
│ ├── multiline_tooltip_standard.py
│ ├── multiple_interactions.py
│ ├── natural_disasters.py
│ ├── normalized_stacked_area_chart.py
│ ├── normalized_stacked_bar_chart.py
│ ├── pacman_chart.py
│ ├── parallel_coordinates.py
│ ├── percentage_of_total.py
│ ├── pie_chart.py
│ ├── pie_chart_with_labels.py
│ ├── polar_bar_chart.py
│ ├── poly_fit_regression.py
│ ├── pyramid.py
│ ├── radial_chart.py
│ ├── ranged_dot_plot.py
│ ├── ridgeline_plot.py
│ ├── scatter_linked_table.py
│ ├── scatter_marginal_hist.py
│ ├── scatter_point_paths_hover.py
│ ├── scatter_with_layered_histogram.py
│ ├── scatter_with_minimap.py
│ ├── scatter_with_rolling_mean.py
│ ├── seattle_weather_interactive.py
│ ├── select_detail.py
│ ├── simple_scatter_with_errorbars.py
│ ├── sorted_error_bars_with_ci.py
│ ├── stacked_bar_chart_sorted_segments.py
│ ├── stacked_bar_chart_with_text.py
│ ├── stem_and_leaf.py
│ ├── streamgraph.py
│ ├── strip_plot_jitter.py
│ ├── top_k_items.py
│ ├── top_k_letters.py
│ ├── top_k_with_others.py
│ ├── us_employment.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
│ ├── wheat_wages.py
│ ├── wilkinson-dot-plot.py
│ ├── wind_vector_map.py
│ └── window_rank.py
├── expr
│ ├── __init__.py
│ └── test_expr.py
├── test_examples.py
├── test_jupyter_chart.py
├── test_magics.py
├── test_toplevel.py
├── test_transformed_data.py
├── utils
│ ├── __init__.py
│ ├── test_compiler.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_to_values_narwhals.py
│ └── test_utils.py
└── vegalite
│ ├── __init__.py
│ ├── test_common.py
│ └── v5
│ ├── __init__.py
│ ├── schema
│ ├── __init__.py
│ └── test_channels.py
│ ├── test_alias.py
│ ├── test_api.py
│ ├── test_data.py
│ ├── test_display.py
│ ├── test_geo_interface.py
│ ├── test_layer_props.py
│ ├── test_params.py
│ ├── test_renderers.py
│ └── test_theme.py
├── tools
├── __init__.py
├── codemod.py
├── fs.py
├── generate_api_docs.py
├── generate_schema_wrapper.py
├── markup.py
├── schemapi
│ ├── __init__.py
│ ├── codegen.py
│ ├── schemapi.py
│ └── utils.py
├── sync_website.py
├── update_init_file.py
├── vega_expr.py
└── versioning.py
└── uv.lock
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto eol=lf
2 |
--------------------------------------------------------------------------------
/.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/vega/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.yml:
--------------------------------------------------------------------------------
1 | name: Feature request
2 | description: Suggest an improvement
3 | labels: ["enhancement"]
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | Thanks for taking the time to suggest a new feature!
9 |
10 | Note that 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 see the Vega-Lite chart specification.
11 |
12 | If you believe this feature is more relevant for Altair than Vega-Lite, then make sure to search for duplicate issues before filling out the form below.
13 | - type: textarea
14 | id: what-happened
15 | attributes:
16 | label: What is your suggestion?
17 | description: Describe the feature's goal, motivating use cases, and its expected behavior.
18 | validations:
19 | required: true
20 | - type: textarea
21 | id: alternative-solutions
22 | attributes:
23 | label: Have you considered any alternative solutions?
24 |
--------------------------------------------------------------------------------
/.github/dependabot.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "github-actions"
4 | directory: "/"
5 | schedule:
6 | interval: "monthly"
7 | groups:
8 | github-actions:
9 | patterns:
10 | - "*"
11 | commit-message:
12 | prefix: "ci"
13 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Thanks for contributing to Altair! 🎉
4 |
5 | Please follow these guidelines:
6 |
7 | ### 1. **PR Description**
8 | - Briefly describe the changes and their purpose. For help, check this [guide](https://medium.com/@greenberg/writing-pull-requests-your-coworkers-might-enjoy-reading-9d0307e93da3).
9 |
10 | ### 2. **Tests & Docs**
11 | - Include unit tests and update documentation for new features.
12 |
13 | ### 3. **Commit Message**
14 | - Use [semantic commit messages](https://www.conventionalcommits.org/), e.g., `"feat: Add embed_options to charts"`.
15 | - Add `!` for breaking changes (e.g., `"fix!: Raise error when embed_options is None"`).
16 |
17 | ### 4. **PR Title Types**
18 | - **feat**: New feature
19 | - **fix**: Bug fix
20 | - **docs**: Documentation changes
21 | - **style**: Code style changes (no functionality change)
22 | - **refactor**: Code restructuring
23 | - **perf**: Performance improvements
24 | - **test**: Add or fix tests
25 | - **build**: Changes to build system or dependencies
26 | - **ci**: CI configuration changes
27 | - **chore**: Miscellaneous tasks
28 | - **revert**: Reverts a commit
29 |
--------------------------------------------------------------------------------
/.github/release.yml:
--------------------------------------------------------------------------------
1 | changelog:
2 | categories:
3 | - title: Breaking
4 | labels:
5 | - breaking
6 | - title: Deprecation
7 | labels:
8 | - deprecation
9 | - title: Enhancements
10 | labels:
11 | - enhancement
12 | - title: Bug Fixes
13 | labels:
14 | - bug
15 | - title: Maintainance
16 | labels:
17 | - maintainance
18 | - title: Documentation
19 | labels:
20 | - documentation
21 | - title: Other Changes
22 | labels:
23 | - "*"
24 |
--------------------------------------------------------------------------------
/.github/workflows/check-pr.yml:
--------------------------------------------------------------------------------
1 | name: "Lint PR"
2 |
3 | on:
4 | pull_request_target:
5 | types:
6 | - opened
7 | - edited
8 | - synchronize
9 |
10 | permissions:
11 | pull-requests: read
12 |
13 | jobs:
14 | main:
15 | name: Validate PR title
16 | runs-on: ubuntu-latest
17 | steps:
18 | - uses: amannn/action-semantic-pull-request@v5
19 | env:
20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
21 |
--------------------------------------------------------------------------------
/.github/workflows/docbuild.yml:
--------------------------------------------------------------------------------
1 | name: docbuild
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v4
10 | - name: Set up Python 3.12
11 | uses: actions/setup-python@v5
12 | with:
13 | python-version: "3.12"
14 | - name: Install uv
15 | uses: astral-sh/setup-uv@v5
16 | with:
17 | enable-cache: true
18 | cache-dependency-glob: |
19 | **/uv.lock
20 | **/pyproject.toml
21 | - name: Install dependencies
22 | run: uv sync --all-extras
23 | - name: Build docs
24 | run: |
25 | mkdir -p doc/_images
26 | uv run sphinx-build -b html -d doc/_build/doctrees doc doc/_build/html
27 | - name: Run doctests
28 | run: |
29 | uv run sphinx-build -b doctest -d doc/_build/doctrees doc doc/_build/doctest
30 |
31 |
32 |
--------------------------------------------------------------------------------
/.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: ruff-mypy
9 | steps:
10 | - name: "Set up Python"
11 | uses: actions/setup-python@v5
12 | with:
13 | python-version: "3.12"
14 | - uses: actions/checkout@v4
15 | - name: Install uv
16 | uses: astral-sh/setup-uv@v5
17 | with:
18 | enable-cache: true
19 | cache-dependency-glob: |
20 | **/uv.lock
21 | **/pyproject.toml
22 | # Installing all dependencies and not just the linters as mypy needs them for type checking
23 | - name: Install dependencies
24 | run: uv sync --all-extras
25 | - name: ruff check (lint)
26 | run: |
27 | uv run ruff check
28 | - name: ruff format
29 | run: |
30 | uv run ruff format --check --diff
31 | - name: mypy (type check)
32 | run: |
33 | uv run mypy altair tests
34 |
--------------------------------------------------------------------------------
/.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 | venv
12 | .venv
13 | build/
14 | develop-eggs/
15 | dist/
16 | downloads/
17 | eggs/
18 | .eggs/
19 | lib/
20 | lib64/
21 | parts/
22 | sdist/
23 | var/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *,cover
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 |
55 | # Sphinx documentation
56 | docs/_build/
57 |
58 | # PyBuilder
59 | target/
60 |
61 | # emacs backups
62 | *~
63 | \#*\#
64 |
65 | .ipynb_checkpoints
66 | .idea/*
67 | tools/_build
68 | Untitled*.ipynb
69 | .mypy*
70 | .pytest_cache
71 | *.DS_Store
72 |
73 | # VSCode
74 | .vscode
75 |
76 | # hatch, doc generation
77 | data.json
78 |
79 | # type stubs
80 | typings/
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | As a project of the Vega Organization, we use the [Vega Code of Conduct](https://github.com/vega/.github/blob/main/CODE_OF_CONDUCT.md).
4 |
--------------------------------------------------------------------------------
/altair/expr/consts.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | CONST_LISTING = {
4 | "NaN": "not a number (same as JavaScript literal NaN)",
5 | "LN10": "the natural log of 10 (alias to Math.LN10)",
6 | "E": "the transcendental number e (alias to Math.E)",
7 | "LOG10E": "the base 10 logarithm e (alias to Math.LOG10E)",
8 | "LOG2E": "the base 2 logarithm of e (alias to Math.LOG2E)",
9 | "SQRT1_2": "the square root of 0.5 (alias to Math.SQRT1_2)",
10 | "LN2": "the natural log of 2 (alias to Math.LN2)",
11 | "SQRT2": "the square root of 2 (alias to Math.SQRT1_2)",
12 | "PI": "the transcendental number pi (alias to Math.PI)",
13 | }
14 |
--------------------------------------------------------------------------------
/altair/jupyter/__init__.py:
--------------------------------------------------------------------------------
1 | try:
2 | import anywidget # noqa: F401
3 | except ImportError:
4 | # When anywidget isn't available, create stand-in JupyterChart class
5 | # that raises an informative import error on construction. This
6 | # way we can make JupyterChart available in the altair namespace
7 | # when anywidget is not installed
8 | class JupyterChart:
9 | def __init__(self, *args, **kwargs):
10 | msg = (
11 | "The Altair JupyterChart requires the anywidget \n"
12 | "Python package which may be installed using pip with\n"
13 | " pip install anywidget\n"
14 | "or using conda with\n"
15 | " conda install -c conda-forge anywidget\n"
16 | "Afterwards, you will need to restart your Python kernel."
17 | )
18 | raise ImportError(msg)
19 |
20 | else:
21 | from .jupyter_chart import JupyterChart # noqa: F401
22 |
--------------------------------------------------------------------------------
/altair/jupyter/js/README.md:
--------------------------------------------------------------------------------
1 | # JupyterChart
2 | This directory contains the JavaScript portion of the Altair `JupyterChart`. The `JupyterChart` is based on the [AnyWidget](https://anywidget.dev/) project.
3 |
--------------------------------------------------------------------------------
/altair/py.typed:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/altair/py.typed
--------------------------------------------------------------------------------
/altair/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from .core import (
2 | SHORTHAND_KEYS,
3 | display_traceback,
4 | infer_encoding_types,
5 | infer_vegalite_type_for_pandas,
6 | parse_shorthand,
7 | sanitize_narwhals_dataframe,
8 | sanitize_pandas_dataframe,
9 | update_nested,
10 | use_signature,
11 | )
12 | from .deprecation import AltairDeprecationWarning, deprecated, deprecated_warn
13 | from .html import spec_to_html
14 | from .plugin_registry import PluginRegistry
15 | from .schemapi import (
16 | VERSIONS,
17 | Optional,
18 | SchemaBase,
19 | SchemaLike,
20 | Undefined,
21 | is_undefined,
22 | )
23 |
24 | __all__ = (
25 | "SHORTHAND_KEYS",
26 | "VERSIONS",
27 | "AltairDeprecationWarning",
28 | "Optional",
29 | "PluginRegistry",
30 | "SchemaBase",
31 | "SchemaLike",
32 | "Undefined",
33 | "deprecated",
34 | "deprecated_warn",
35 | "display_traceback",
36 | "infer_encoding_types",
37 | "infer_vegalite_type_for_pandas",
38 | "is_undefined",
39 | "parse_shorthand",
40 | "sanitize_narwhals_dataframe",
41 | "sanitize_pandas_dataframe",
42 | "spec_to_html",
43 | "update_nested",
44 | "use_signature",
45 | )
46 |
--------------------------------------------------------------------------------
/altair/utils/compiler.py:
--------------------------------------------------------------------------------
1 | from collections.abc import Callable
2 | from typing import Any
3 |
4 | from altair.utils import PluginRegistry
5 |
6 | # ==============================================================================
7 | # Vega-Lite to Vega compiler registry
8 | # ==============================================================================
9 | VegaLiteCompilerType = Callable[[dict[str, Any]], dict[str, Any]]
10 |
11 |
12 | class VegaLiteCompilerRegistry(PluginRegistry[VegaLiteCompilerType, dict[str, Any]]):
13 | pass
14 |
--------------------------------------------------------------------------------
/altair/vegalite/__init__.py:
--------------------------------------------------------------------------------
1 | # ruff: noqa: F403
2 | from .v5 import *
3 |
--------------------------------------------------------------------------------
/altair/vegalite/api.py:
--------------------------------------------------------------------------------
1 | # ruff: noqa
2 | from .v5.api import *
3 |
--------------------------------------------------------------------------------
/altair/vegalite/display.py:
--------------------------------------------------------------------------------
1 | from altair.utils.display import (
2 | DefaultRendererReturnType,
3 | Displayable,
4 | HTMLRenderer,
5 | RendererRegistry,
6 | default_renderer_base,
7 | json_renderer_base,
8 | )
9 |
10 | __all__ = (
11 | "DefaultRendererReturnType",
12 | "Displayable",
13 | "HTMLRenderer",
14 | "RendererRegistry",
15 | "default_renderer_base",
16 | "json_renderer_base",
17 | )
18 |
--------------------------------------------------------------------------------
/altair/vegalite/schema.py:
--------------------------------------------------------------------------------
1 | """Altair schema wrappers."""
2 |
3 | # ruff: noqa: F403
4 | from .v5.schema import *
5 |
--------------------------------------------------------------------------------
/altair/vegalite/v5/compiler.py:
--------------------------------------------------------------------------------
1 | from typing import Final
2 |
3 | from altair.utils._importers import import_vl_convert
4 | from altair.utils.compiler import VegaLiteCompilerRegistry
5 |
6 | ENTRY_POINT_GROUP: Final = "altair.vegalite.v5.vegalite_compiler"
7 | vegalite_compilers = VegaLiteCompilerRegistry(entry_point_group=ENTRY_POINT_GROUP)
8 |
9 |
10 | def vl_convert_compiler(vegalite_spec: dict) -> dict:
11 | """Vega-Lite to Vega compiler that uses vl-convert."""
12 | from . import SCHEMA_VERSION
13 |
14 | vlc = import_vl_convert()
15 |
16 | # Compute vl-convert's vl_version string (of the form 'v5_8')
17 | # from SCHEMA_VERSION (of the form 'v5.8.0')
18 | vl_version = "_".join(SCHEMA_VERSION.split(".")[:2])
19 | return vlc.vegalite_to_vega(vegalite_spec, vl_version=vl_version)
20 |
21 |
22 | vegalite_compilers.register("vl-convert", vl_convert_compiler)
23 | vegalite_compilers.enable("vl-convert")
24 |
--------------------------------------------------------------------------------
/design/altair-logo-light.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/design/altair-logo-light.png
--------------------------------------------------------------------------------
/design/altair-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/design/altair-logo.png
--------------------------------------------------------------------------------
/doc/.gitignore:
--------------------------------------------------------------------------------
1 | _build
2 |
3 | # gallery is auto-generated; don't version-control it
4 | gallery
5 | _images
6 |
7 | # generated class documentation
8 | user_guide/generated
9 |
--------------------------------------------------------------------------------
/doc/_static/altair-logo-light.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/altair-logo-light.png
--------------------------------------------------------------------------------
/doc/_static/altair-plot.css:
--------------------------------------------------------------------------------
1 | .vega-actions a {
2 | margin-right: 12px;
3 | color: #757575;
4 | font-weight: normal;
5 | font-size: 13px;
6 | }
7 |
8 | .vega-embed {
9 | margin-bottom: 20px;
10 | margin-top: 20px;
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/doc/_static/chart.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/doc/_static/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/favicon.ico
--------------------------------------------------------------------------------
/doc/_static/gray-square.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/gray-square.png
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/accessing_variable_params.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/accessing_variable_params.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/index_selection_param.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/index_selection_param.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/interval_selection_param.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/interval_selection_param.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/linking_interval_selection.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/linking_interval_selection.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/linking_variable_params.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/linking_variable_params.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/linking_variable_params2.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/linking_variable_params2.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/observing_variable_params.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/observing_variable_params.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/point_selection_param.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/point_selection_param.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/setting_variable_params.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/setting_variable_params.mov
--------------------------------------------------------------------------------
/doc/_static/jupyter_chart/updating_charts.mov:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/doc/_static/jupyter_chart/updating_charts.mov
--------------------------------------------------------------------------------
/doc/_static/theme_overrides.css:
--------------------------------------------------------------------------------
1 | /* override table width restrictions */
2 | @media screen and (min-width: 767px) {
3 |
4 | .wy-table-responsive table td {
5 | /* !important prevents the common CSS stylesheets from overriding
6 | this as on RTD they are loaded after this stylesheet */
7 | white-space: normal !important;
8 | }
9 | .wy-table-responsive {
10 | overflow: visible !important;
11 | }
12 | }
13 |
14 | .rst-content dl:not(.docutils) dt em {
15 | font-style: normal !important;
16 | line-height: 1.4em !important;
17 | }
18 |
19 | .rst-content div[class^='highlight'] {
20 | background: #fff !important;
21 | }
22 |
23 | img.logo {
24 | width: 120px !important;
25 | }
26 |
27 | /* Increase max-width of the content area slightly to accommodate larger screens */
28 | .bd-main .bd-content .bd-article-container {
29 | max-width: 1000px;
30 | }
31 |
--------------------------------------------------------------------------------
/doc/_templates/class.rst:
--------------------------------------------------------------------------------
1 | :mod:`{{module}}`.{{objname}}
2 | {{ underline }}==============
3 |
4 | .. currentmodule:: {{ module }}
5 |
6 | .. autoclass:: {{ objname }}
7 |
8 | {% block methods %}
9 | .. automethod:: __init__
10 | {% endblock %}
11 |
12 | .. raw:: html
13 |
14 |
15 |
--------------------------------------------------------------------------------
/doc/_templates/navbar-project.html:
--------------------------------------------------------------------------------
1 |
2 | {{ project }}
3 |
4 |
5 |
--------------------------------------------------------------------------------
/doc/_templates/sidebar-logo.html:
--------------------------------------------------------------------------------
1 |
14 |
--------------------------------------------------------------------------------
/doc/about/code_of_conduct.rst:
--------------------------------------------------------------------------------
1 | Code of Conduct
2 | ===============
3 |
4 | As a project of the Vega Organization, we use the `Vega Code of Conduct `.
5 |
--------------------------------------------------------------------------------
/doc/about/governance.rst:
--------------------------------------------------------------------------------
1 | Governance
2 | ==========
3 | Vega-Altair's governance structure is based on GitHub's
4 | `Minimum Viable Governance `_ (MVG) template.
5 |
6 | Organizational Governance
7 | -------------------------
8 | The Altair-Viz organization is governed by the documents that reside in the
9 | `Vega Organizational GitHub repository `_.
10 |
11 | Project Governance
12 | ------------------
13 | The Vega-Altair library is governed by the documents that reside in the
14 | `project-docs `_ directory of
15 | the Vega Organizational GitHub repository.
--------------------------------------------------------------------------------
/doc/about/roadmap.rst:
--------------------------------------------------------------------------------
1 | Roadmap
2 | =======
3 |
4 | The roadmap for Vega-Altair and related projects can be found in
5 | `this project board `_.
6 |
7 | .. toctree::
8 | :maxdepth: 1
9 | :caption: About
10 | :hidden:
11 |
12 | self
13 | code_of_conduct
14 | governance
15 | citing
16 | versioning
17 |
--------------------------------------------------------------------------------
/doc/case_studies/index.rst:
--------------------------------------------------------------------------------
1 | Tutorials
2 | ---------
3 |
4 | These tutorials explore more advanced use cases than the gallery.
5 |
6 | .. toctree::
7 | :hidden:
8 |
9 | exploring-weather
10 | numpy-tooltip-images
11 |
--------------------------------------------------------------------------------
/doc/getting_started/getting_help.rst:
--------------------------------------------------------------------------------
1 | Getting Help
2 | ============
3 |
4 | Altair is BSD-licensed and the source is available on `GitHub`_,
5 | where you can also report `bugs and feature requests`_.
6 | For general questions, please ask on `StackOverflow`_
7 | using the `altair` tag.
8 |
9 | You can browse this documentation
10 | via the links in the top navigation panel
11 | or by viewing the full site :ref:`genindex`.
12 | In addition to reading this documentation page,
13 | it can be helpful to also browse the `Vega-Lite documentation `_.
14 |
15 | .. _GitHub: http://github.com/vega/altair
16 | .. _Git Issues: http://github.com/vega/altair/issues
17 | .. _Vega: http://vega.github.io/vega
18 | .. _Vega-Lite: http://vega.github.io/vega-lite
19 | .. _bugs and feature requests: https://github.com/vega/altair/issues/new/choose
20 | .. _StackOverflow: https://stackoverflow.com/tags/altair
21 |
--------------------------------------------------------------------------------
/doc/releases/changes.rst:
--------------------------------------------------------------------------------
1 | :orphan:
2 |
3 | Release Notes
4 | =============
5 |
6 | We have moved the release notes to GitHub. You can now find them `here `_.
7 |
--------------------------------------------------------------------------------
/doc/user_guide/marks/circle.rst:
--------------------------------------------------------------------------------
1 | .. currentmodule:: altair
2 |
3 | .. _user-guide-circle-marks:
4 |
5 | Circle
6 | ~~~~~~
7 |
8 | ``circle`` mark is similar to ``point`` mark, except that (1) the ``shape`` value is always set to ``circle`` (2) they are filled by default.
9 |
10 | Circle Mark Properties
11 | ^^^^^^^^^^^^^^^^^^^^^^
12 | A ``circle`` mark definition can contain any :ref:`standard mark properties `
13 | and the following special properties:
14 |
15 | .. altair-object-table:: altair.MarkDef
16 | :properties: size
17 |
18 | Scatter Plot with Circle
19 | ^^^^^^^^^^^^^^^^^^^^^^^^
20 |
21 | Here is an example scatter plot with ``circle`` marks:
22 |
23 | .. altair-plot::
24 | import altair as alt
25 | from vega_datasets import data
26 |
27 | source = data.cars.url
28 |
29 | alt.Chart(source).mark_circle().encode(
30 | x=("Horsepower:Q"),
31 | y=("Miles_per_Gallon:Q"),
32 | )
33 |
34 |
35 |
--------------------------------------------------------------------------------
/doc/user_guide/marks/square.rst:
--------------------------------------------------------------------------------
1 | .. currentmodule:: altair
2 |
3 | .. _user-guide-square-marks:
4 |
5 | Square
6 | ~~~~~~
7 | ``square`` mark is similar to ``point`` mark, except that (1) the ``shape`` value is always set to ``square`` (2) they are filled by default.
8 |
9 | Square Mark Properties
10 | ----------------------
11 | A ``square`` mark definition can contain any :ref:`standard mark properties `
12 | and the following special properties:
13 |
14 | .. altair-object-table:: altair.MarkDef
15 | :properties: size
16 |
17 | Scatter Plot with Square
18 | ------------------------
19 | .. altair-plot::
20 | import altair as alt
21 | from vega_datasets import data
22 |
23 | source = data.cars()
24 |
25 | alt.Chart(source).mark_square().encode(
26 | x="Horsepower:Q",
27 | y="Miles_per_Gallon:Q",
28 | )
29 |
--------------------------------------------------------------------------------
/doc/user_guide/transform/loess.rst:
--------------------------------------------------------------------------------
1 | .. currentmodule:: altair
2 |
3 | .. _user-guide-loess-transform:
4 |
5 | LOESS
6 | ~~~~~
7 | The LOESS transform (LOcally Estimated Scatterplot Smoothing) uses a
8 | locally-estimated regression to produce a trend line.
9 | LOESS performs a sequence of local weighted regressions over a sliding
10 | window of nearest-neighbor points. For standard parametric regression options,
11 | see the :ref:`user-guide-regression-transform`.
12 |
13 | Here is an example of using LOESS to smooth samples from a Gaussian random walk:
14 |
15 | .. altair-plot::
16 |
17 | import altair as alt
18 | import pandas as pd
19 | import numpy as np
20 |
21 | np.random.seed(42)
22 |
23 | df = pd.DataFrame({
24 | 'x': range(100),
25 | 'y': np.random.randn(100).cumsum()
26 | })
27 |
28 | chart = alt.Chart(df).mark_point().encode(
29 | x='x',
30 | y='y'
31 | )
32 |
33 | chart + chart.transform_loess('x', 'y').mark_line()
34 |
35 |
36 | Transform Options
37 | ^^^^^^^^^^^^^^^^^
38 | The :meth:`~Chart.transform_loess` method is built on the
39 | :class:`~LoessTransform` class, which has the following options:
40 |
41 | .. altair-object-table:: altair.LoessTransform
42 |
--------------------------------------------------------------------------------
/doc/user_guide/transform/quantile.rst:
--------------------------------------------------------------------------------
1 | .. currentmodule:: altair
2 |
3 | .. _user-guide-quantile-transform:
4 |
5 | Quantile
6 | ~~~~~~~~
7 | The quantile transform calculates empirical `quantile `_
8 | values for input data. If a groupby parameter is provided, quantiles are estimated
9 | separately per group. Among other uses, the quantile transform is useful for creating
10 | `quantile-quantile (Q-Q) plots `_.
11 |
12 | Here is an example of a quantile plot of normally-distributed data:
13 |
14 | .. altair-plot::
15 |
16 | import altair as alt
17 | import pandas as pd
18 | import numpy as np
19 |
20 | np.random.seed(42)
21 | df = pd.DataFrame({'x': np.random.randn(200)})
22 |
23 | alt.Chart(df).transform_quantile(
24 | 'x', step=0.01
25 | ).mark_point().encode(
26 | x='prob:Q',
27 | y='value:Q'
28 | )
29 |
30 | Transform Options
31 | ^^^^^^^^^^^^^^^^^
32 | The :meth:`~Chart.transform_quantile` method is built on the :class:`~QuantileTransform`
33 | class, which has the following options:
34 |
35 | .. altair-object-table:: altair.QuantileTransform
36 |
--------------------------------------------------------------------------------
/doc/user_guide/transform/sample.rst:
--------------------------------------------------------------------------------
1 | .. currentmodule:: altair
2 |
3 | .. _user-guide-sample-transform:
4 |
5 | Sample
6 | ~~~~~~
7 | The sample transform is one of the simpler of all Altair's data transforms;
8 | it takes a single parameter ``sample`` which specified a number of rows to
9 | randomly choose from the dataset. The resulting chart will be created using
10 | only this random subset of the data.
11 |
12 | For example, here we chart the full cars dataset alongside a sample of 100
13 | rows:
14 |
15 | .. altair-plot::
16 |
17 | import altair as alt
18 | from vega_datasets import data
19 |
20 | source = data.cars.url
21 |
22 | chart = alt.Chart(source).mark_point().encode(
23 | x='Horsepower:Q',
24 | y='Miles_per_Gallon:Q',
25 | color='Origin:N'
26 | ).properties(
27 | width=200,
28 | height=200
29 | )
30 |
31 | chart | chart.transform_sample(100)
32 |
33 |
34 | Transform Options
35 | ^^^^^^^^^^^^^^^^^
36 | The :meth:`~Chart.transform_sample` method is built on the :class:`~SampleTransform`
37 | class, which has the following options:
38 |
39 | .. altair-object-table:: altair.SampleTransform
40 |
--------------------------------------------------------------------------------
/images/cars.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/images/cars.png
--------------------------------------------------------------------------------
/images/cars_scatter_bar.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/images/cars_scatter_bar.gif
--------------------------------------------------------------------------------
/paper/seattle_weather_interactive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/paper/seattle_weather_interactive.png
--------------------------------------------------------------------------------
/sphinxext/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/sphinxext/__init__.py
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import Set
3 |
4 | # Set of the names of examples that should have SVG static images.
5 | # This is for examples that VlConvert's PNG export does not support.
6 | SVG_EXAMPLES: Set[str] = {"isotype_emoji"}
7 |
8 |
9 | def iter_examples_arguments_syntax():
10 | """Iterate over the examples in this directory.
11 |
12 | Each item is a dict with the following keys:
13 | - "name" : the unique name of the example
14 | - "filename" : the full file path to the example
15 | - "use_svg": Flag indicating whether the static image for the
16 | example should be an SVG instead of a PNG
17 | """
18 | examples_arguments_syntax_dir = os.path.abspath(os.path.dirname(__file__))
19 | for filename in os.listdir(examples_arguments_syntax_dir):
20 | name, ext = os.path.splitext(filename)
21 | if name.startswith("_") or ext != ".py":
22 | continue
23 | yield {
24 | "name": name,
25 | "filename": os.path.join(examples_arguments_syntax_dir, filename),
26 | "use_svg": name in SVG_EXAMPLES,
27 | }
28 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/annual_weather_heatmap.py:
--------------------------------------------------------------------------------
1 | """
2 | Annual Weather Heatmap
3 | ----------------------
4 | """
5 | # category: tables
6 | import altair as alt
7 | from vega_datasets import data
8 |
9 | source = data.seattle_weather()
10 |
11 | alt.Chart(source, title="Daily Max Temperatures (C) in Seattle, WA").mark_rect().encode(
12 | x=alt.X("date(date):O", title="Day", axis=alt.Axis(format="%e", labelAngle=0)),
13 | y=alt.Y("month(date):O", title="Month"),
14 | color=alt.Color("max(temp_max)", legend=alt.Legend(title=None)),
15 | tooltip=[
16 | alt.Tooltip("monthdate(date)", title="Date"),
17 | alt.Tooltip("max(temp_max)", title="Max Temp"),
18 | ],
19 | ).configure_view(step=13, strokeWidth=0).configure_axis(domain=False)
20 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/anscombe_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Anscombe's Quartet
3 | ------------------
4 |
5 | `Anscombe's Quartet `_
6 | is a famous dataset constructed by Francis Anscombe.
7 | It is made of 4 different subsets of data.
8 | Each subset has very different characteristics, even though common summary
9 | statistics such as mean and variance are identical.
10 |
11 | This example shows how to make a faceted plot, with each facet
12 | showing a different subset of the data.
13 | """
14 | # category: case studies
15 | import altair as alt
16 | from vega_datasets import data
17 |
18 | source = data.anscombe()
19 |
20 | alt.Chart(source).mark_circle().encode(
21 | alt.X("X", scale=alt.Scale(zero=False)),
22 | alt.Y("Y", scale=alt.Scale(zero=False)),
23 | alt.Facet("Series", columns=2),
24 | ).properties(
25 | width=180,
26 | height=180,
27 | )
28 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/area_faceted.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Area Chart
3 | ------------------
4 | Multiple area subcharts, one for each company.
5 | We also show filtering out one of the companies,
6 | and sorting the companies in a custom order.
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | # If the `year` column equals `1810`
13 | # then, set the bar color to `"orange"`
14 | # otherwise, use `"steelblue"`
15 | color = alt.when(year=1810).then(alt.value("orange")).otherwise(alt.value("steelblue"))
16 |
17 | alt.Chart(source).mark_bar().encode(
18 | x="year:O",
19 | y="wheat:Q",
20 | color=color
21 | ).properties(width=600)
22 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | # category: bar charts
7 | import altair as alt
8 | import pandas as pd
9 | from vega_datasets import data
10 |
11 | source = data.wheat()
12 | threshold = pd.DataFrame([{"threshold": 90}])
13 |
14 | bars = alt.Chart(source).mark_bar().encode(
15 | x="year:O",
16 | y="wheat:Q",
17 | )
18 |
19 | highlight = alt.Chart(source).mark_bar(color="#e45755").encode(
20 | x='year:O',
21 | y='baseline:Q',
22 | y2='wheat:Q'
23 | ).transform_filter(
24 | alt.datum.wheat > 90
25 | ).transform_calculate("baseline", "90")
26 |
27 | rule = alt.Chart(threshold).mark_rule().encode(
28 | y='threshold:Q'
29 | )
30 |
31 | (bars + highlight + rule).properties(width=600)
32 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
11 | source = data.wheat()
12 |
13 | base = alt.Chart(source).encode(
14 | x='wheat',
15 | y="year:O",
16 | text='wheat'
17 | )
18 | base.mark_bar() + base.mark_text(align='left', dx=2)
19 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_chart_with_labels_measured_luminance.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Labels based on Measured Luminance
3 | =================================================
4 | This example shows a basic horizontal bar chart with labels where the measured luminance to decides if the text overlay is be colored ``black`` or ``white``.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.barley()
11 |
12 | base = alt.Chart(source).encode(
13 | x=alt.X('sum(yield):Q', stack='zero'),
14 | y=alt.Y('site:O', sort='-x'),
15 | text=alt.Text('sum(yield):Q', format='.0f')
16 | )
17 |
18 | bars = base.mark_bar(
19 | tooltip=alt.expr("luminance(scale('color', datum.sum_yield))")
20 | ).encode(
21 | color='sum(yield):Q'
22 | )
23 |
24 | text = base.mark_text(
25 | align='right',
26 | dx=-3,
27 | color=alt.expr("luminance(scale('color', datum.sum_yield)) > 0.5 ? 'black' : 'white'")
28 | )
29 |
30 | bars + text
31 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_chart_with_mean_line.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Line at Mean
3 | ---------------------------
4 | This example shows the mean value overlaid 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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | predicate = alt.datum.nonfarm_change > 0
13 | color = alt.when(predicate).then(alt.value("steelblue")).otherwise(alt.value("orange"))
14 |
15 | alt.Chart(source).mark_bar().encode(
16 | x="month:T",
17 | y="nonfarm_change:Q",
18 | color=color
19 | ).properties(width=600)
20 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_chart_with_range.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Range
3 | ====================
4 | This example shows a range bar chart where each bar displays information of a low and high value.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.seattle_weather()
11 |
12 | bar = alt.Chart(source).mark_bar(cornerRadius=10, height=10).encode(
13 | x=alt.X('min(temp_min):Q', scale=alt.Scale(domain=[-15, 45]), title='Temperature (°C)'),
14 | x2='max(temp_max):Q',
15 | y=alt.Y('month(date):O', title=None)
16 | )
17 |
18 | text_min = alt.Chart(source).mark_text(align='right', dx=-5).encode(
19 | x='min(temp_min):Q',
20 | y=alt.Y('month(date):O'),
21 | text='min(temp_min):Q'
22 | )
23 |
24 | text_max = alt.Chart(source).mark_text(align='left', dx=5).encode(
25 | x='max(temp_max):Q',
26 | y=alt.Y('month(date):O'),
27 | text='max(temp_max):Q'
28 | )
29 |
30 | (bar + text_min + text_max).properties(
31 | title=alt.Title(text='Temperature variation by month', subtitle='Seatle weather, 2012-2015')
32 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_chart_with_single_threshold.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart Highlighting Values beyond a Threshold
3 | ------------------------------------------------
4 | This example shows a bar chart highlighting values beyond a threshold.
5 | """
6 | # category: bar charts
7 | import pandas as pd
8 | import altair as alt
9 |
10 | source = pd.DataFrame({
11 | "Day": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
12 | "Value": [55, 112, 65, 38, 80, 138, 120, 103, 395, 200, 72, 51, 112, 175, 131]
13 | })
14 | threshold = 300
15 |
16 | bars = alt.Chart(source).mark_bar(color="steelblue").encode(
17 | x="Day:O",
18 | y="Value:Q",
19 | )
20 |
21 | highlight = bars.mark_bar(color="#e45755").encode(
22 | y2=alt.Y2(datum=threshold)
23 | ).transform_filter(
24 | alt.datum.Value > threshold
25 | )
26 |
27 | rule = alt.Chart().mark_rule().encode(
28 | y=alt.Y(datum=threshold)
29 | )
30 |
31 | label = rule.mark_text(
32 | x="width",
33 | dx=-2,
34 | align="right",
35 | baseline="bottom",
36 | text="hazardous"
37 | )
38 |
39 | (bars + highlight + rule + label)
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_faceted_stacked.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Stacked Bar Chart
3 | =========================
4 | A horizontal stacked bar chart using barley crop yield data.
5 | The chart is horizontally faceted based on the year,
6 | and vertically faceted based on variety.
7 | """
8 | # category: bar charts
9 | import altair as alt
10 | from vega_datasets import data
11 |
12 | source = data.barley()
13 |
14 | alt.Chart(source).mark_bar().encode(
15 | column="year:O",
16 | x="yield",
17 | y="variety",
18 | color="site",
19 | ).properties(width=220)
20 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/bar_with_rolling_mean.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Rolling Mean
3 | ---------------------------
4 | A bar chart overlaid 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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/beckers_barley_wrapped_facet.py:
--------------------------------------------------------------------------------
1 | """
2 | Becker's Barley Wrapped Facet Plot
3 | ----------------------------------
4 | The example demonstrates the faceted charts created by Richard Becker,
5 | William Cleveland and others in the 1990s. Using the visualization technique
6 | where each row is a different site (i.e. the chart is faceted by site),
7 | they identified an anomaly in a widely used agriculatural dataset,
8 | where the "Morris" site accidentally had the years 1931 and 1932 swapped.
9 | They named this
10 | `"The Morris Mistake." `_.
11 | """
12 | # category: case studies
13 | import altair as alt
14 | from vega_datasets import data
15 |
16 | source = data.barley.url
17 |
18 | alt.Chart(source).mark_point().encode(
19 | alt.X("median(yield):Q", scale=alt.Scale(zero=False)),
20 | y="variety:O",
21 | color="year:N",
22 | facet=alt.Facet("site:O", columns=2),
23 | ).properties(
24 | width=200,
25 | height=100,
26 | )
27 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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="6MS"),"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 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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=alt.Y("cumulative_count:Q", stack=False)
21 | )
22 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/density_repeat.py:
--------------------------------------------------------------------------------
1 | """
2 | Repeated Density Estimates
3 | --------------------------
4 | Density estimates for each feature of iris flower.
5 | This is what we call a "repeated" plot, with one subplot
6 | for each feature.
7 | """
8 | # category: distributions
9 |
10 | import altair as alt
11 | from vega_datasets import data
12 |
13 | source = data.iris()
14 |
15 | alt.Chart(source).transform_fold(
16 | [
17 | "petalWidth",
18 | "petalLength",
19 | "sepalWidth",
20 | "sepalLength",
21 | ],
22 | as_=["Measurement_type", "value"],
23 | ).transform_density(
24 | density="value",
25 | bandwidth=0.3,
26 | groupby=["Measurement_type"],
27 | extent=[0, 8],
28 | ).mark_area().encode(
29 | alt.X("value:Q"),
30 | alt.Y("density:Q"),
31 | alt.Row("Measurement_type:N"),
32 | ).properties(
33 | width=300, height=50
34 | )
35 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/distributions_faceted_histogram.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Histogram
3 | -----------------
4 | This example shows how to make a basic faceted histogram,
5 | with one histogram subplot for different subsets of the data.
6 |
7 | Based off the vega-lite example:
8 | https://vega.github.io/vega-lite/examples/trellis_bar_histogram.html
9 | """
10 | # category: distributions
11 | import altair as alt
12 | from vega_datasets import data
13 |
14 | source = data.cars()
15 |
16 | alt.Chart(source).mark_bar().encode(
17 | alt.X("Horsepower:Q", bin=True),
18 | y="count()",
19 | row="Origin",
20 | )
21 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/empirical_cumulative_distribution_function.py:
--------------------------------------------------------------------------------
1 | """
2 | Empirical Cumulative Distribution Function
3 | ------------------------------------------
4 | This example shows an empirical cumulative distribution function.
5 | """
6 | # category: distributions
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.movies.url
11 |
12 | alt.Chart(source).transform_window(
13 | ecdf="cume_dist()",
14 | sort=[{"field": "IMDB_Rating"}],
15 | ).mark_line(
16 | interpolate="step-after"
17 | ).encode(
18 | x="IMDB_Rating:Q",
19 | y="ecdf:Q"
20 | )
21 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/errorbars_with_ci.py:
--------------------------------------------------------------------------------
1 | """
2 | Error Bars with 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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/errorbars_with_std.py:
--------------------------------------------------------------------------------
1 | """
2 | Error Bars 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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/gantt_chart.py:
--------------------------------------------------------------------------------
1 | """
2 | Gantt Chart
3 | -----------------
4 | This example shows how to make a simple Gantt chart.
5 | """
6 | # category: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/groupby-map.py:
--------------------------------------------------------------------------------
1 | """
2 | Grouped Points with Proportional Symbols Map
3 | ============================================
4 | This is a layered geographic visualization that groups points by state.
5 | """
6 | # category: maps
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | airports = data.airports.url
11 | states = alt.topo_feature(data.us_10m.url, feature='states')
12 |
13 | # US states background
14 | background = alt.Chart(states).mark_geoshape(
15 | fill='lightgray',
16 | stroke='white'
17 | ).properties(
18 | width=500,
19 | height=300
20 | ).project('albersUsa')
21 |
22 | # Airports grouped by state
23 | points = alt.Chart(airports).transform_aggregate(
24 | latitude='mean(latitude)',
25 | longitude='mean(longitude)',
26 | count='count()',
27 | groupby=['state']
28 | ).mark_circle().encode(
29 | longitude='longitude:Q',
30 | latitude='latitude:Q',
31 | size=alt.Size('count:Q', title='Number of Airports'),
32 | color=alt.value('steelblue'),
33 | tooltip=['state:N','count:Q']
34 | ).properties(
35 | title='Number of airports in US'
36 | )
37 |
38 | background + points
39 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/grouped_bar_chart_overlapping_bars.py:
--------------------------------------------------------------------------------
1 | """
2 | Grouped Bar Chart with xOffset and overlapping bars
3 | ---------------------------------------------------
4 | Like :ref:`gallery_grouped_bar_chart2`, this example shows a grouped bar chart using the ``xOffset`` encoding channel, but in this example the bars are partly overlapping within each group.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | import pandas as pd
9 |
10 | source = pd.DataFrame(
11 | {
12 | "category": list("AABBCC"),
13 | "group": list("xyxyxy"),
14 | "value": [0.1, 0.6, 0.7, 0.2, 0.6, 0.1],
15 | }
16 | )
17 |
18 | base = alt.Chart(source, width=alt.Step(12)).encode(
19 | x="category:N",
20 | y="value:Q",
21 | xOffset=alt.XOffset("group:N", scale=alt.Scale(paddingOuter=0.5)),
22 | )
23 |
24 | alt.layer(
25 | base.mark_bar(size=20, stroke="white", fillOpacity=0.9).encode(fill="group:N"),
26 | base.mark_text(dy=-5).encode(text="value:Q"),
27 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/histogram_gradient_color.py:
--------------------------------------------------------------------------------
1 | """
2 | Histogram with Gradient Color
3 | -----------------------------
4 | This example shows how to make a histogram with gradient color.
5 | The low-high IMDB rating is represented with the color scheme `pinkyellowgreen`.
6 | """
7 | # category: distributions
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",
15 | bin=alt.Bin(maxbins=20),
16 | scale=alt.Scale(domain=[1, 10])
17 | ),
18 | alt.Y('count()'),
19 | alt.Color("IMDB_Rating:Q",
20 | bin=alt.Bin(maxbins=20),
21 | scale=alt.Scale(scheme='pinkyellowgreen')
22 | )
23 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/histogram_heatmap.py:
--------------------------------------------------------------------------------
1 | """
2 | 2D Histogram Heatmap
3 | --------------------
4 | This example shows how to make a heatmap from binned quantitative data.
5 | """
6 | # category: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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_params(brush)
35 | )
36 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/histogram_scatterplot.py:
--------------------------------------------------------------------------------
1 | """
2 | 2D Histogram Scatter Plot
3 | -------------------------
4 | This example shows how to make a 2d histogram scatter plot.
5 | """
6 | # category: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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_interval()
14 |
15 | alt.Chart(source).mark_point().encode(
16 | x='Horsepower:Q',
17 | y='Miles_per_Gallon:Q',
18 | color=alt.when(brush).then("Cylinders:O").otherwise(alt.value("grey")),
19 | ).add_params(brush)
20 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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_point`` when projected over a single field or encoding.
7 | """
8 | # category: interactive charts
9 | import altair as alt
10 | from vega_datasets import data
11 |
12 | source = data.unemployment_across_industries.url
13 |
14 | selection = alt.selection_point(fields=['series'], bind='legend')
15 |
16 | alt.Chart(source).mark_area().encode(
17 | alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
18 | alt.Y('sum(count):Q', stack='center', axis=None),
19 | alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
20 | opacity=alt.when(selection).then(alt.value(1)).otherwise(alt.value(0.2))
21 | ).add_params(
22 | selection
23 | )
24 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/interactive_reorder_stacked_bars.py:
--------------------------------------------------------------------------------
1 | """
2 | Reorder stacked bar segments
3 | ============================
4 | This example uses a calculate transform
5 | to check the values of the "site" column
6 | vs the clicked values in the legend,
7 | and assigns a lower order (0)
8 | if there is a match.
9 | The use of "indexOf" checks for equality in an array,
10 | which here allows for multiple segments to be reordered
11 | by holding down the shift key while clicking the legend.
12 | """
13 | # category: interactive charts
14 | import altair as alt
15 | from vega_datasets import data
16 |
17 | selection = alt.selection_point(fields=['site'], bind='legend')
18 |
19 | source = data.barley.url
20 |
21 | alt.Chart(source).mark_bar().transform_calculate(
22 | site_order=f"if({selection.name}.site && indexof({selection.name}.site, datum.site) !== -1, 0, 1)"
23 | ).encode(
24 | x='sum(yield):Q',
25 | y='variety:N',
26 | color='site:N',
27 | order='site_order:N',
28 | opacity=alt.when(selection).then(alt.value(0.9)).otherwise(alt.value(0.2))
29 | ).add_params(
30 | selection
31 | )
32 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/interactive_scatter_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Simple Interactive Colored Scatter Plot
3 | ---------------------------------------
4 | This example shows how to make an interactive scatter plot.
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/interval_selection.py:
--------------------------------------------------------------------------------
1 | """
2 | Interval Selection with Initial Date Range
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. The initial
7 | selection range is set using Python's native datetime objects.
8 | """
9 | # category: interactive charts
10 | import altair as alt
11 | from vega_datasets import data
12 | import datetime as dt
13 |
14 | source = data.sp500.url
15 |
16 | date_range = (dt.date(2007, 6, 30), dt.date(2009, 6, 30))
17 |
18 | brush = alt.selection_interval(encodings=['x'],
19 | value={'x': date_range})
20 |
21 | base = alt.Chart(source).mark_area().encode(
22 | x = 'date:T',
23 | y = 'price:Q'
24 | ).properties(
25 | width=600,
26 | height=200
27 | )
28 |
29 | upper = base.encode(
30 | alt.X('date:T', scale=alt.Scale(domain=brush))
31 | )
32 |
33 | lower = base.properties(
34 | height=60
35 | ).add_params(brush)
36 |
37 | upper & lower
38 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/isotype_grid.py:
--------------------------------------------------------------------------------
1 | """
2 | Isotype Grid
3 | ------------
4 | This example is a grid of isotype figures.
5 | """
6 | # category: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/lasagna_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Lasagna Plot (Dense Time-Series Heatmap)
3 | ----------------------------------------
4 | """
5 | # category: tables
6 | import altair as alt
7 | from vega_datasets import data
8 |
9 | source = data.stocks()
10 |
11 | color_condition = (
12 | alt.when(alt.expr.month("datum.value") == 1, alt.expr.date("datum.value") == 1)
13 | .then(alt.value("black"))
14 | .otherwise(alt.value(None))
15 | )
16 |
17 | alt.Chart(source, width=300, height=100).transform_filter(
18 | alt.datum.symbol != "GOOG"
19 | ).mark_rect().encode(
20 | x=alt.X(
21 | "yearmonthdate(date):O",
22 | axis=alt.Axis(
23 | format="%Y",
24 | labelAngle=0,
25 | labelOverlap=False,
26 | labelColor=color_condition,
27 | tickColor=color_condition,
28 | ),
29 | title="Time",
30 | ),
31 | y=alt.Y("symbol:N", title=None),
32 | color=alt.Color("sum(price)", title="Price"),
33 | )
34 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: tables
8 | import altair as alt
9 | from vega_datasets import data
10 |
11 | source = data.cars()
12 |
13 | # Configure common options. We specify the aggregation
14 | # as a transform here so we can reuse it in both layers.
15 | base = alt.Chart(source).transform_aggregate(
16 | mean_horsepower='mean(Horsepower)',
17 | groupby=['Origin', 'Cylinders']
18 | ).encode(
19 | alt.X('Cylinders:O'),
20 | alt.Y('Origin:O'),
21 | )
22 |
23 | # Configure heatmap
24 | heatmap = base.mark_rect().encode(
25 | color=alt.Color('mean_horsepower:Q',
26 | scale=alt.Scale(scheme='viridis'),
27 | legend=alt.Legend(title="Mean of Horsepower"),
28 | )
29 | )
30 |
31 | color = (
32 | alt.when(alt.datum.mean_horsepower > 150)
33 | .then(alt.value("black"))
34 | .otherwise(alt.value("white"))
35 | )
36 | # Configure text
37 | text = base.mark_text(baseline='middle').encode(
38 | text=alt.Text('mean_horsepower:Q', format=".0f"), color=color
39 | )
40 |
41 | # Draw the chart
42 | heatmap + text
43 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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)
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_chart_with_custom_legend.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Custom Legend
3 | -----------------------------
4 | This example uses the argmax aggregation function in order to create a custom
5 | legend for a line chart.
6 | """
7 | # category: line charts
8 | import altair as alt
9 | from vega_datasets import data
10 |
11 |
12 | source = data.stocks()
13 |
14 | base = alt.Chart(source).encode(
15 | color=alt.Color("symbol", legend=None)
16 | ).transform_filter(
17 | "datum.symbol !== 'IBM'"
18 | ).properties(
19 | width=500
20 | )
21 |
22 | line = base.mark_line().encode(x="date", y="price")
23 |
24 |
25 | last_price = base.mark_circle().encode(
26 | x=alt.X("last_date['date']:T"),
27 | y=alt.Y("last_date['price']:Q")
28 | ).transform_aggregate(
29 | last_date="argmax(date)",
30 | groupby=["symbol"]
31 | )
32 |
33 | company_name = last_price.mark_text(align="left", dx=4).encode(text="symbol")
34 |
35 | chart = (line + last_price + company_name).encode(
36 | x=alt.X(title="date"),
37 | y=alt.Y(title="price")
38 | )
39 |
40 | chart
41 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_chart_with_interpolation.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Interpolation
3 | -----------------------------
4 | This chart shows a line chart with the path interpolated. A full list of interpolation methods is available `in the documentation `_.
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_line(interpolate="monotone").encode(
13 | x="date:T",
14 | y="price:Q",
15 | color="symbol:N"
16 | )
17 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_chart_with_points.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Point Markers
3 | -----------------------------
4 | This chart shows a simple line chart with points marking each value.
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_line(point=True).encode(
13 | x='date:T',
14 | y='price:Q',
15 | color='symbol:N'
16 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_chart_with_points_stroked.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Stroked Point Markers
3 | -------------------------------------
4 | This example shows a simple line chart with points in a different color.
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_line(
13 | point=alt.OverlayMarkDef(filled=False, fill="white")
14 | ).encode(
15 | x='date:T',
16 | y='price:Q',
17 | color='symbol:N'
18 | )
19 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_custom_order.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Custom Order
3 | ----------------------------
4 | By default, the line's path (order of points in the line) is
5 | determined by data values on the temporal/ordinal field.
6 | However, a field can be mapped to the order channel for a custom path.
7 |
8 | For example, to show a pattern of data change over time between
9 | gasoline price and average miles driven per capita we use
10 | order channel to sort the points in the line by time field (year).
11 | The earliest year (1956) is one endpoint and the latest year (2010)
12 | is the other endpoint.
13 |
14 | This is based on Hannah Fairfield's article 'Driving Shifts Into Reverse'.
15 | See https://archive.nytimes.com/www.nytimes.com/imagepages/2010/05/02/business/02metrics.html.
16 | """
17 | # category: line charts
18 | import altair as alt
19 | from vega_datasets import data
20 |
21 | source = data.driving()
22 |
23 | alt.Chart(source).mark_line(point=True).encode(
24 | alt.X("miles", scale=alt.Scale(zero=False)),
25 | alt.Y("gas", scale=alt.Scale(zero=False)),
26 | order="year",
27 | tooltip=["miles", "gas", "year"],
28 | )
29 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/line_with_last_value_labeled.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Last Value Labeled
3 | ----------------------------------
4 | This chart shows a line chart with a label annotating the final value
5 | """
6 | # category: line charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | # Import example data
11 | source = data.stocks()
12 |
13 | # Create a common chart object
14 | # Use `transform_filter` to reduce the dataset to clarify our example. Not required.
15 | chart = (
16 | alt.Chart(source)
17 | .transform_filter(alt.datum.symbol != "IBM")
18 | .encode(color=alt.Color("symbol", legend=None))
19 | )
20 |
21 | # Draw the line
22 | line = chart.mark_line().encode(x="date:T", y="price:Q")
23 |
24 | # Use the `argmax` aggregate to limit the dataset to the final value
25 | label = chart.encode(
26 | x=alt.X("max(date):T"),
27 | y=alt.Y("price:Q", aggregate=alt.ArgmaxDef(argmax="date")),
28 | text="symbol",
29 | )
30 |
31 | # Create a text label
32 | text = label.mark_text(align="left", dx=4)
33 |
34 | # Create a circle annotation
35 | circle = label.mark_circle()
36 |
37 | # Draw the chart with all the layers combined
38 | line + circle + text
39 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/multi_series_line.py:
--------------------------------------------------------------------------------
1 | """
2 | Multiple Series Line Chart
3 | --------------------------
4 |
5 | This example shows how to make a line chart with multiple series of data.
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:T',
15 | y='price:Q',
16 | color='symbol:N',
17 | )
18 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/multiline_highlight.py:
--------------------------------------------------------------------------------
1 | """
2 | Multi-Line Highlight
3 | ====================
4 | This multi-line chart uses an invisible Voronoi tessellation to handle pointerover 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_point(on='pointerover',
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_params(
27 | highlight
28 | ).properties(
29 | width=600
30 | )
31 |
32 | lines = base.mark_line().encode(
33 | size=alt.when(~highlight).then(alt.value(1)).otherwise(alt.value(3))
34 | )
35 |
36 | points + lines
37 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/parallel_coordinates.py:
--------------------------------------------------------------------------------
1 | """
2 | Parallel Coordinates
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: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/point_map.py:
--------------------------------------------------------------------------------
1 | """
2 | Point map
3 | =========
4 | This is a layered map that shows the positions of airports on a background of U.S. states.
5 | """
6 | # category: maps
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | # Read in points
11 | airports = data.airports()
12 |
13 | # Read in polygons from topojson
14 | states = alt.topo_feature(data.us_10m.url, feature='states')
15 |
16 | # US states background
17 | background = alt.Chart(states).mark_geoshape(
18 | fill='lightgray',
19 | stroke='white'
20 | ).properties(
21 | width=500,
22 | height=300
23 | ).project('albersUsa')
24 |
25 | # airport positions on background
26 | points = alt.Chart(airports).mark_circle(
27 | size=10,
28 | color='steelblue'
29 | ).encode(
30 | longitude='longitude:Q',
31 | latitude='latitude:Q',
32 | tooltip=['name', 'city', 'state']
33 | )
34 |
35 | background + points
36 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/pyramid.py:
--------------------------------------------------------------------------------
1 | """
2 | Pyramid Pie Chart
3 | -----------------
4 | Altair reproduction of http://robslink.com/SAS/democd91/pyramid_pie.htm
5 | """
6 | # category: case studies
7 | import altair as alt
8 | import pandas as pd
9 |
10 | category = ['Sky', 'Shady side of a pyramid', 'Sunny side of a pyramid']
11 | color = ["#416D9D", "#674028", "#DEAC58"]
12 | df = pd.DataFrame({'category': category, 'value': [75, 10, 15]})
13 |
14 | alt.Chart(df).mark_arc(outerRadius=80).encode(
15 | alt.Theta('value:Q', scale=alt.Scale(range=[2.356, 8.639])),
16 | alt.Color('category:N',
17 | scale=alt.Scale(domain=category, range=color),
18 | legend=alt.Legend(title=None, orient='none', legendX=160, legendY=50)),
19 | order='value:Q'
20 | ).properties(width=150, height=150).configure_view(strokeOpacity=0)
21 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/ranged_dot_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Ranged Dot Plot
3 | ---------------
4 | This example shows a ranged dot plot to convey changing life expectancy for the five most populous countries (between 1955 and 2000).
5 | """
6 | # category: advanced calculations
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.countries.url
11 |
12 | chart = (
13 | alt.Chart(source)
14 | .encode(x="life_expect:Q", y="country:N")
15 | .transform_filter(
16 | alt.FieldOneOfPredicate(
17 | field="country",
18 | oneOf=["China", "India", "United States", "Indonesia", "Brazil"],
19 | )
20 | )
21 | .transform_filter(alt.FieldOneOfPredicate(field="year", oneOf=[1955, 2000]))
22 | )
23 |
24 | line = chart.mark_line(color="#db646f").encode(detail="country:N")
25 |
26 | # Add points for life expectancy in 1955 & 2000
27 | color = alt.Color(
28 | "year:O", scale=alt.Scale(domain=[1955, 2000], range=["#e6959c", "#911a24"])
29 | )
30 | points = (
31 | chart.mark_point(
32 | size=100,
33 | opacity=1,
34 | filled=True,
35 | )
36 | .encode(color=color)
37 | .interactive()
38 | )
39 |
40 | (line + points)
41 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/scatter_faceted.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Scatter Plot
3 | --------------------
4 | A series of scatter plots, one for each country/area of origin.
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, width=100, height=100).mark_point().encode(
13 | x="Horsepower:Q",
14 | y="Miles_per_Gallon:Q",
15 | row="Origin:N",
16 | )
17 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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_interval(resolve='global')
14 |
15 | base = alt.Chart(source).mark_point().encode(
16 | y='Miles_per_Gallon',
17 | color=alt.when(brush).then("Origin").otherwise(alt.ColorValue("gray")),
18 | ).add_params(
19 | brush
20 | ).properties(
21 | width=250,
22 | height=250
23 | )
24 |
25 | base.encode(x='Horsepower') | base.encode(x='Acceleration')
26 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/scatter_qq.py:
--------------------------------------------------------------------------------
1 | """
2 | Quantile-Quantile Plot
3 | ----------------------
4 | A quantile-quantile plot comparing input data to theoretical distributions.
5 | """
6 | # category: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 Scatter Plot Smoothing).
6 | """
7 | # category: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/scatter_with_shaded_area.py:
--------------------------------------------------------------------------------
1 | """
2 | Scatter Plot with Shaded Area
3 | -----------------------------
4 | This example shows a scatter plot with shaded area,
5 | constructed using :ref:`area mark ` and :ref:`rect mark `.
6 | """
7 | # category: scatter plots
8 |
9 | import altair as alt
10 | import pandas as pd
11 | import numpy as np
12 |
13 | data = pd.DataFrame({
14 | "x": np.random.uniform(-4, 5, size=50),
15 | "y": np.random.uniform(2, 5, size=50),
16 | })
17 |
18 | rect_data = pd.DataFrame({
19 | "x1": [-2],
20 | "x2": [-1]
21 | })
22 |
23 | # define this interval between y = -x and y = -x
24 | df = pd.DataFrame({
25 | "x": range(7),
26 | "ymin": range(7),
27 | "ymax": range(1,8)
28 | })
29 |
30 | points = alt.Chart(data).mark_point().encode(
31 | x="x",
32 | y="y"
33 | )
34 |
35 | interval = alt.Chart(df).mark_area(opacity=0.3).encode(
36 | x="x:Q",
37 | y="ymin:Q",
38 | y2="ymax:Q"
39 | )
40 |
41 |
42 | rect = alt.Chart(rect_data).mark_rect(opacity=0.3).encode(
43 | x="x1",
44 | x2="x2",
45 | color=alt.ColorValue("#FF0000")
46 | )
47 |
48 | points + interval + rect
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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'])
27 | background = base.add_params(brush)
28 | selected = base.transform_filter(brush).mark_area(color='goldenrod')
29 |
30 | background + selected
31 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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_interval()
15 |
16 | points = alt.Chart(source).mark_point().encode(
17 | x='Horsepower:Q',
18 | y='Miles_per_Gallon:Q',
19 | color=alt.when(brush).then("Origin:N").otherwise(alt.value("lightgray"))
20 | ).add_params(
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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_interval(encodings=['x'])
14 |
15 | bars = alt.Chart().mark_bar().encode(
16 | x='month(date):O',
17 | y='mean(precipitation):Q',
18 | opacity = alt.when(brush).then(alt.value(1)).otherwise(alt.value(0.7)),
19 | ).add_params(
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/selection_zorder.py:
--------------------------------------------------------------------------------
1 | """
2 | Selection zorder
3 | ================
4 | This example shows how to bring selected points to the front/foreground
5 | by using a condition to change the point's (z)order
6 | as it is hovered over with the pointer.
7 | This prevents that the selected points are obscured
8 | by those that are not selected.
9 | """
10 | # category: interactive charts
11 |
12 | import altair as alt
13 | from vega_datasets import data
14 |
15 |
16 | cars = data.cars.url
17 |
18 | hover = alt.selection_point(on='pointerover', nearest=True, empty=False)
19 | when_hover = alt.when(hover)
20 |
21 | chart = alt.Chart(cars, title='Selection obscured by other points').mark_circle(opacity=1).encode(
22 | x='Horsepower:Q',
23 | y='Miles_per_Gallon:Q',
24 | color=when_hover.then(alt.value("coral")).otherwise(alt.value("lightgray")),
25 | size=when_hover.then(alt.value(300)).otherwise(alt.value(30))
26 | ).add_params(
27 | hover
28 | )
29 |
30 | chart | chart.encode(
31 | order=when_hover.then(alt.value(1)).otherwise(alt.value(0))
32 | ).properties(
33 | title='Selection brought to front'
34 | )
35 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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.param(bind=slider, value=50)
20 | predicate = alt.datum.xval < cutoff
21 |
22 | alt.Chart(df).mark_point().encode(
23 | x='xval',
24 | y='yval',
25 | color=alt.when(predicate).then(alt.value("red")).otherwise(alt.value("blue")),
26 | ).add_params(
27 | cutoff
28 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: advanced calculations
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 | )
28 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/top_k_with_others.py:
--------------------------------------------------------------------------------
1 | """
2 | Top-K Plot with Others
3 | ----------------------
4 | This example shows how to use aggregate, window, and calculate transformations
5 | to display the top-k directors by average worldwide gross while grouping the
6 | remaining directors as 'All Others'.
7 | """
8 | # category: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 | )
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/wilkinson-dot-plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Wilkinson Dot Plot
3 | ------------------
4 | An example of a `Wilkinson Dot Plot `_
5 | """
6 | # category: advanced calculations
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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_arguments_syntax/world_projections.py:
--------------------------------------------------------------------------------
1 | """
2 | World Projections
3 | -----------------
4 | This example shows a map of the countries of the world.
5 | Use the dropdown menu to compare projections. For more details on the `project` arguments, see the API of `altair.Projection `_.
6 | """
7 | # category: maps
8 | import altair as alt
9 | from vega_datasets import data
10 |
11 | source = alt.topo_feature(data.world_110m.url, 'countries')
12 |
13 | input_dropdown = alt.binding_select(options=[
14 | "albers",
15 | "albersUsa",
16 | "azimuthalEqualArea",
17 | "azimuthalEquidistant",
18 | "conicEqualArea",
19 | "conicEquidistant",
20 | "equalEarth",
21 | "equirectangular",
22 | "gnomonic",
23 | "mercator",
24 | "naturalEarth1",
25 | "orthographic",
26 | "stereographic",
27 | "transverseMercator"
28 | ], name='Projection ')
29 | param_projection = alt.param(value="equalEarth", bind=input_dropdown)
30 |
31 | alt.Chart(source, width=500, height=300).mark_geoshape(
32 | fill='lightgray',
33 | stroke='gray'
34 | ).project(
35 | type=alt.expr(param_projection.name)
36 | ).add_params(param_projection)
37 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import Set
3 |
4 | # Set of the names of examples that should have SVG static images.
5 | # This is for examples that VlConvert's PNG export does not support.
6 | SVG_EXAMPLES: Set[str] = {"isotype_emoji"}
7 |
8 |
9 | def iter_examples_methods_syntax():
10 | """Iterate over the examples in this directory.
11 |
12 | Each item is a dict with the following keys:
13 | - "name" : the unique name of the example
14 | - "filename" : the full file path to the example
15 | """
16 | examples_methods_syntax_dir = os.path.abspath(os.path.dirname(__file__))
17 | for filename in os.listdir(examples_methods_syntax_dir):
18 | name, ext = os.path.splitext(filename)
19 | if name.startswith("_") or ext != ".py":
20 | continue
21 | yield {
22 | "name": name,
23 | "filename": os.path.join(examples_methods_syntax_dir, filename),
24 | "use_svg": name in SVG_EXAMPLES,
25 | }
26 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/annual_weather_heatmap.py:
--------------------------------------------------------------------------------
1 | """
2 | Annual Weather Heatmap
3 | ----------------------
4 | """
5 | # category: tables
6 | import altair as alt
7 | from vega_datasets import data
8 |
9 | source = data.seattle_weather()
10 |
11 | alt.Chart(source, title="Daily Max Temperatures (C) in Seattle, WA").mark_rect().encode(
12 | alt.X("date(date):O").title("Day").axis(format="%e", labelAngle=0),
13 | alt.Y("month(date):O").title("Month"),
14 | alt.Color("max(temp_max)").title(None),
15 | tooltip=[
16 | alt.Tooltip("monthdate(date)", title="Date"),
17 | alt.Tooltip("max(temp_max)", title="Max Temp"),
18 | ],
19 | ).configure_view(
20 | step=13,
21 | strokeWidth=0
22 | ).configure_axis(
23 | domain=False
24 | )
25 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/anscombe_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Anscombe's Quartet
3 | ------------------
4 |
5 | `Anscombe's Quartet `_
6 | is a famous dataset constructed by Francis Anscombe.
7 | It is made of 4 different subsets of data.
8 | Each subset has very different characteristics, even though common summary
9 | statistics such as mean and variance are identical.
10 |
11 | This example shows how to make a faceted plot, with each facet
12 | showing a different subset of the data.
13 | """
14 | # category: case studies
15 | import altair as alt
16 | from vega_datasets import data
17 |
18 | source = data.anscombe()
19 |
20 | alt.Chart(source).mark_circle().encode(
21 | alt.X("X").scale(zero=False),
22 | alt.Y("Y").scale(zero=False),
23 | alt.Facet("Series", columns=2),
24 | ).properties(
25 | width=180,
26 | height=180,
27 | )
28 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/area_faceted.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Area Chart
3 | ------------------
4 | Multiple area subcharts, one for each company.
5 | We also show filtering out one of the companies,
6 | and sorting the companies in a custom order.
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(alt.datum.symbol != "GOOG").mark_area().encode(
15 | x="date:T",
16 | y="price:Q",
17 | color="symbol:N",
18 | row=alt.Row("symbol:N").sort(["MSFT", "AAPL", "IBM", "AMZN"]),
19 | ).properties(height=50, width=400)
20 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/bar_chart_with_labels_measured_luminance.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Labels based on Measured Luminance
3 | =================================================
4 | This example shows a basic horizontal bar chart with labels where the measured luminance to decides if the text overlay is be colored ``black`` or ``white``.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.barley()
11 |
12 | base = alt.Chart(source).encode(
13 | x=alt.X('sum(yield):Q').stack('zero'),
14 | y=alt.Y('site:O').sort('-x'),
15 | text=alt.Text('sum(yield):Q', format='.0f')
16 | )
17 |
18 | bars = base.mark_bar(
19 | tooltip=alt.expr("luminance(scale('color', datum.sum_yield))")
20 | ).encode(
21 | color='sum(yield):Q'
22 | )
23 |
24 | text = base.mark_text(
25 | align='right',
26 | dx=-3,
27 | color=alt.expr("luminance(scale('color', datum.sum_yield)) > 0.5 ? 'black' : 'white'")
28 | )
29 |
30 | bars + text
31 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/bar_chart_with_range.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart with Range
3 | ====================
4 | This example shows a range bar chart where each bar displays information of a low and high value.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.seattle_weather()
11 |
12 | bar = alt.Chart(source).mark_bar(cornerRadius=10, height=10).encode(
13 | x=alt.X('min(temp_min):Q').scale(domain=[-15, 45]).title('Temperature (°C)'),
14 | x2='max(temp_max):Q',
15 | y=alt.Y('month(date):O').title(None)
16 | )
17 |
18 | text_min = alt.Chart(source).mark_text(align='right', dx=-5).encode(
19 | x='min(temp_min):Q',
20 | y=alt.Y('month(date):O'),
21 | text='min(temp_min):Q'
22 | )
23 |
24 | text_max = alt.Chart(source).mark_text(align='left', dx=5).encode(
25 | x='max(temp_max):Q',
26 | y=alt.Y('month(date):O'),
27 | text='max(temp_max):Q'
28 | )
29 |
30 | (bar + text_min + text_max).properties(
31 | title=alt.Title(text='Temperature variation by month', subtitle='Seatle weather, 2012-2015')
32 | )
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/bar_chart_with_single_threshold.py:
--------------------------------------------------------------------------------
1 | """
2 | Bar Chart Highlighting Values beyond a Threshold
3 | ------------------------------------------------
4 | This example shows a bar chart highlighting values beyond a threshold.
5 | """
6 | # category: bar charts
7 | import pandas as pd
8 | import altair as alt
9 |
10 | source = pd.DataFrame({
11 | "Day": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
12 | "Value": [55, 112, 65, 38, 80, 138, 120, 103, 395, 200, 72, 51, 112, 175, 131]
13 | })
14 | threshold = 300
15 |
16 | bars = alt.Chart(source).mark_bar(color="steelblue").encode(
17 | x="Day:O",
18 | y="Value:Q",
19 | )
20 |
21 | highlight = bars.mark_bar(color="#e45755").encode(
22 | y2=alt.Y2(datum=threshold)
23 | ).transform_filter(
24 | alt.datum.Value > threshold
25 | )
26 |
27 | rule = alt.Chart().mark_rule().encode(
28 | y=alt.Y(datum=threshold)
29 | )
30 |
31 | label = rule.mark_text(
32 | x="width",
33 | dx=-2,
34 | align="right",
35 | baseline="bottom",
36 | text="hazardous"
37 | )
38 |
39 | (bars + highlight + rule + label)
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/beckers_barley_wrapped_facet.py:
--------------------------------------------------------------------------------
1 | """
2 | Becker's Barley Wrapped Facet Plot
3 | ----------------------------------
4 | The example demonstrates the faceted charts created by Richard Becker,
5 | William Cleveland and others in the 1990s. Using the visualization technique
6 | where each row is a different site (i.e. the chart is faceted by site),
7 | they identified an anomaly in a widely used agriculatural dataset,
8 | where the "Morris" site accidentally had the years 1931 and 1932 swapped.
9 | They named this
10 | `"The Morris Mistake." `_.
11 | """
12 | # category: case studies
13 | import altair as alt
14 | from vega_datasets import data
15 |
16 | source = data.barley.url
17 |
18 | alt.Chart(source).mark_point().encode(
19 | alt.X("median(yield):Q").scale(zero=False),
20 | y="variety:O",
21 | color="year:N",
22 | facet=alt.Facet("site:O", columns=2),
23 | ).properties(
24 | width=200,
25 | height=100,
26 | )
27 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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="6MS"),"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 | )
30 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
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=alt.Y("cumulative_count:Q").stack(False)
21 | )
22 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/distributions_faceted_histogram.py:
--------------------------------------------------------------------------------
1 | """
2 | Faceted Histogram
3 | -----------------
4 | This example shows how to make a basic faceted histogram,
5 | with one histogram subplot for different subsets of the data.
6 |
7 | Based off the vega-lite example:
8 | https://vega.github.io/vega-lite/examples/trellis_bar_histogram.html
9 | """
10 | # category: distributions
11 | import altair as alt
12 | from vega_datasets import data
13 |
14 | source = data.cars()
15 |
16 | alt.Chart(source).mark_bar().encode(
17 | alt.X("Horsepower:Q").bin(),
18 | y="count()",
19 | row="Origin",
20 | )
21 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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({
14 | "category": [1, 2, 3, 4, 5, 6],
15 | "value": [4, 6, 10, 3, 7, 8]
16 | })
17 |
18 | alt.Chart(source).mark_arc(innerRadius=50).encode(
19 | theta="value",
20 | color="category:N",
21 | )
22 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/errorbars_with_ci.py:
--------------------------------------------------------------------------------
1 | """
2 | Error Bars with 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: uncertainties and trends
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 | alt.X('yield').scale(zero=False),
16 | alt.Y('variety')
17 | )
18 |
19 | points = alt.Chart(source).mark_point(filled=True, color='black').encode(
20 | x=alt.X('mean(yield)'),
21 | y=alt.Y('variety'),
22 | )
23 |
24 | error_bars + points
25 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/errorbars_with_std.py:
--------------------------------------------------------------------------------
1 | """
2 | Error Bars 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: uncertainties and trends
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').scale(zero=False),
15 | y=alt.Y('variety')
16 | )
17 |
18 | points = alt.Chart(source).mark_point(filled=True, color='black').encode(
19 | x=alt.X('mean(yield)'),
20 | y=alt.Y('variety'),
21 | )
22 |
23 | error_bars + points
24 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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(type='log'),
16 | alt.Y('health:Q').scale(zero=False),
17 | size='population:Q'
18 | )
19 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/groupby-map.py:
--------------------------------------------------------------------------------
1 | """
2 | Grouped Points with Proportional Symbols Map
3 | ============================================
4 | This is a layered geographic visualization that groups points by state.
5 | """
6 | # category: maps
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | airports = data.airports.url
11 | states = alt.topo_feature(data.us_10m.url, feature='states')
12 |
13 | # US states background
14 | background = alt.Chart(states).mark_geoshape(
15 | fill='lightgray',
16 | stroke='white'
17 | ).properties(
18 | width=500,
19 | height=300
20 | ).project('albersUsa')
21 |
22 | # Airports grouped by state
23 | points = alt.Chart(airports, title='Number of airports in US').transform_aggregate(
24 | latitude='mean(latitude)',
25 | longitude='mean(longitude)',
26 | count='count()',
27 | groupby=['state']
28 | ).mark_circle().encode(
29 | longitude='longitude:Q',
30 | latitude='latitude:Q',
31 | size=alt.Size('count:Q').title('Number of Airports'),
32 | color=alt.value('steelblue'),
33 | tooltip=['state:N','count:Q']
34 | )
35 |
36 | background + points
37 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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({
12 | "Category":list("AAABBBCCC"),
13 | "Group":list("xyzxyzxyz"),
14 | "Value":[0.1, 0.6, 0.9, 0.7, 0.2, 1.1, 0.6, 0.1, 0.2]
15 | })
16 |
17 | alt.Chart(source).mark_bar().encode(
18 | x="Category:N",
19 | y="Value:Q",
20 | xOffset="Group:N",
21 | color="Group:N"
22 | )
23 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/grouped_bar_chart_overlapping_bars.py:
--------------------------------------------------------------------------------
1 | """
2 | Grouped Bar Chart with xOffset and overlapping bars
3 | ---------------------------------------------------
4 | Like :ref:`gallery_grouped_bar_chart2`, this example shows a grouped bar chart using the ``xOffset`` encoding channel, but in this example the bars are partly overlapping within each group.
5 | """
6 | # category: bar charts
7 | import altair as alt
8 | import pandas as pd
9 |
10 | source = pd.DataFrame(
11 | {
12 | "category": list("AABBCC"),
13 | "group": list("xyxyxy"),
14 | "value": [0.1, 0.6, 0.7, 0.2, 0.6, 0.1],
15 | }
16 | )
17 |
18 | base = alt.Chart(source, width=alt.Step(12)).encode(
19 | x="category:N",
20 | y="value:Q",
21 | xOffset=alt.XOffset("group:N").scale(paddingOuter=0.5),
22 | )
23 |
24 | alt.layer(
25 | base.mark_bar(size=20, stroke="white", fillOpacity=0.9).encode(fill="group:N"),
26 | base.mark_text(dy=-5).encode(text="value:Q"),
27 | )
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/histogram_gradient_color.py:
--------------------------------------------------------------------------------
1 | """
2 | Histogram with Gradient Color
3 | -----------------------------
4 | This example shows how to make a histogram with gradient color.
5 | The low-high IMDB rating is represented with the color scheme `pinkyellowgreen`.
6 | """
7 | # category: distributions
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(maxbins=20).scale(domain=[1, 10]),
15 | alt.Y('count()'),
16 | alt.Color("IMDB_Rating:Q").bin(maxbins=20).scale(scheme='pinkyellowgreen')
17 | )
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/histogram_heatmap.py:
--------------------------------------------------------------------------------
1 | """
2 | 2D Histogram Heatmap
3 | --------------------
4 | This example shows how to make a heatmap from binned quantitative data.
5 | """
6 | # category: distributions
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(maxbins=60),
14 | alt.Y('Rotten_Tomatoes_Rating:Q').bin(maxbins=40),
15 | alt.Color('count():Q').scale(scheme='greenblue')
16 | )
17 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
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(maxbins=30, extent=brush)
29 | .scale(domain=brush)
30 | ),
31 | base.encode(
32 | alt.X('time:Q').bin(maxbins=30),
33 | ).add_params(brush)
34 | )
35 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/histogram_scatterplot.py:
--------------------------------------------------------------------------------
1 | """
2 | 2D Histogram Scatter Plot
3 | -------------------------
4 | This example shows how to make a 2d histogram scatter plot.
5 | """
6 | # category: distributions
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(),
14 | alt.Y('Rotten_Tomatoes_Rating:Q').bin(),
15 | size='count()'
16 | )
17 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
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 | alt.X('IMDB_Rating:Q').bin().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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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_point`` when projected over a single field or encoding.
7 | """
8 | # category: interactive charts
9 | import altair as alt
10 | from vega_datasets import data
11 |
12 | source = data.unemployment_across_industries.url
13 |
14 | selection = alt.selection_point(fields=['series'], bind='legend')
15 |
16 | alt.Chart(source).mark_area().encode(
17 | alt.X('yearmonth(date):T').axis(domain=False, format='%Y', tickSize=0),
18 | alt.Y('sum(count):Q').stack('center').axis(None),
19 | alt.Color('series:N').scale(scheme='category20b'),
20 | opacity=alt.when(selection).then(alt.value(1)).otherwise(alt.value(0.2))
21 | ).add_params(
22 | selection
23 | )
24 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/interval_selection.py:
--------------------------------------------------------------------------------
1 | """
2 | Interval Selection with Initial Date Range
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. The initial
7 | selection range is set using Python's native datetime objects.
8 | """
9 | # category: interactive charts
10 | import altair as alt
11 | from vega_datasets import data
12 | import datetime as dt
13 |
14 | source = data.sp500.url
15 |
16 | date_range = (dt.date(2007, 6, 30), dt.date(2009, 6, 30))
17 |
18 | brush = alt.selection_interval(encodings=['x'],
19 | value={'x': date_range})
20 |
21 | base = alt.Chart(source, width=600, height=200).mark_area().encode(
22 | x = 'date:T',
23 | y = 'price:Q'
24 | )
25 |
26 | upper = base.encode(
27 | alt.X('date:T').scale(domain=brush)
28 | )
29 |
30 | lower = base.properties(
31 | height=60
32 | ).add_params(brush)
33 |
34 | upper & lower
35 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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(
13 | source,
14 | title=alt.Title(
15 | "Iowa's green energy boom",
16 | subtitle="A growing share of the state's energy has come from renewable sources"
17 | )
18 | ).mark_area().encode(
19 | alt.X("year:T").title("Year"),
20 | alt.Y("net_generation:Q")
21 | .title("Share of net generation")
22 | .stack("normalize")
23 | .axis(format=".0%"),
24 | alt.Color("source:N").title("Electricity source")
25 | )
26 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/isotype_grid.py:
--------------------------------------------------------------------------------
1 | """
2 | Isotype Grid
3 | ------------
4 | This example is a grid of isotype figures.
5 | """
6 | # category: advanced calculations
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 | alt.X("col:O").axis(None),
31 | alt.Y("row:O").axis(None),
32 | alt.ShapeValue(person)
33 | ).properties(
34 | width=400,
35 | height=400
36 | ).configure_view(
37 | strokeWidth=0
38 | )
39 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/lasagna_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Lasagna Plot (Dense Time-Series Heatmap)
3 | ----------------------------------------
4 | """
5 | # category: tables
6 | import altair as alt
7 | from vega_datasets import data
8 |
9 | source = data.stocks()
10 |
11 | color_condition = (
12 | alt.when(alt.expr.month("datum.value") == 1, alt.expr.date("datum.value") == 1)
13 | .then(alt.value("black"))
14 | .otherwise(alt.value(None))
15 | )
16 |
17 | alt.Chart(source, width=300, height=100).transform_filter(
18 | alt.datum.symbol != "GOOG"
19 | ).mark_rect().encode(
20 | alt.X("yearmonthdate(date):O")
21 | .title("Time")
22 | .axis(
23 | format="%Y",
24 | labelAngle=0,
25 | labelOverlap=False,
26 | labelColor=color_condition,
27 | tickColor=color_condition,
28 | ),
29 | alt.Y("symbol:N").title(None),
30 | alt.Color("sum(price)").title("Price")
31 | )
32 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: advanced calculations
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').title(None)
15 | )
16 |
17 | area = base.mark_area(opacity=0.3, color='#57A44C').encode(
18 | alt.Y('average(temp_max)').axis(title='Avg. Temperature (°C)', titleColor='#57A44C'),
19 | alt.Y2('average(temp_min)')
20 | )
21 |
22 | line = base.mark_line(stroke='#5276A7', interpolate='monotone').encode(
23 | alt.Y('average(precipitation)').axis(title='Precipitation (inches)', titleColor='#5276A7')
24 | )
25 |
26 | alt.layer(area, line).resolve_scale(
27 | y='independent'
28 | )
29 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: tables
8 | import altair as alt
9 | from vega_datasets import data
10 |
11 | source = data.cars()
12 |
13 | # Configure common options. We specify the aggregation
14 | # as a transform here so we can reuse it in both layers.
15 | base = alt.Chart(source).transform_aggregate(
16 | mean_horsepower='mean(Horsepower)',
17 | groupby=['Origin', 'Cylinders']
18 | ).encode(
19 | alt.X('Cylinders:O'),
20 | alt.Y('Origin:O'),
21 | )
22 |
23 | # Configure heatmap
24 | heatmap = base.mark_rect().encode(
25 | alt.Color('mean_horsepower:Q')
26 | .scale(scheme='viridis')
27 | .title("Mean of Horsepower")
28 | )
29 |
30 | color = (
31 | alt.when(alt.datum.mean_horsepower > 150)
32 | .then(alt.value("black"))
33 | .otherwise(alt.value("white"))
34 | )
35 |
36 | # Configure text
37 | text = base.mark_text(baseline='middle').encode(
38 | alt.Text('mean_horsepower:Q', format=".0f"), color=color
39 | )
40 |
41 | # Draw the chart
42 | heatmap + text
43 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
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(maxbins=100),
27 | alt.Y('count()').stack(None),
28 | alt.Color('Experiment:N')
29 | )
30 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/line_chart_with_color_datum.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Datum for Color
3 | -------------------------------
4 | An example of using ``repeat`` inside ``datum`` 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 | alt.X("IMDB_Rating").bin(True),
17 | alt.Y(alt.repeat("layer"))
18 | .aggregate("mean")
19 | .title("Mean of US and Worldwide Gross"),
20 | color=alt.datum(alt.repeat("layer")),
21 | ).repeat(
22 | layer=["US_Gross", "Worldwide_Gross"]
23 | )
24 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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, width=600).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 | )
25 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/line_chart_with_custom_legend.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Custom Legend
3 | -----------------------------
4 | This example uses the argmax aggregation function in order to create a custom
5 | legend for a line chart.
6 | """
7 | # category: line charts
8 | import altair as alt
9 | from vega_datasets import data
10 |
11 |
12 | source = data.stocks()
13 |
14 | base = alt.Chart(source).encode(
15 | alt.Color("symbol").legend(None)
16 | ).transform_filter(
17 | "datum.symbol !== 'IBM'"
18 | ).properties(
19 | width=500
20 | )
21 |
22 | line = base.mark_line().encode(x="date", y="price")
23 |
24 |
25 | last_price = base.mark_circle().encode(
26 | alt.X("last_date['date']:T"),
27 | alt.Y("last_date['price']:Q")
28 | ).transform_aggregate(
29 | last_date="argmax(date)",
30 | groupby=["symbol"]
31 | )
32 |
33 | company_name = last_price.mark_text(align="left", dx=4).encode(text="symbol")
34 |
35 | chart = (line + last_price + company_name).encode(
36 | x=alt.X().title("date"),
37 | y=alt.Y().title("price")
38 | )
39 |
40 | chart
41 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/line_custom_order.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Custom Order
3 | ----------------------------
4 | By default, the line's path (order of points in the line) is
5 | determined by data values on the temporal/ordinal field.
6 | However, a field can be mapped to the order channel for a custom path.
7 |
8 | For example, to show a pattern of data change over time between
9 | gasoline price and average miles driven per capita we use
10 | order channel to sort the points in the line by time field (year).
11 | The earliest year (1956) is one endpoint and the latest year (2010)
12 | is the other endpoint.
13 |
14 | This is based on Hannah Fairfield's article 'Driving Shifts Into Reverse'.
15 | See https://archive.nytimes.com/www.nytimes.com/imagepages/2010/05/02/business/02metrics.html.
16 | """
17 | # category: line charts
18 | import altair as alt
19 | from vega_datasets import data
20 |
21 | source = data.driving()
22 |
23 | alt.Chart(source).mark_line(point=True).encode(
24 | x=alt.X("miles").scale(zero=False),
25 | y=alt.Y("gas").scale(zero=False),
26 | order="year",
27 | tooltip=["miles", "gas", "year"],
28 | )
29 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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(format='%'),
15 | alt.Color('sex:N')
16 | ).transform_filter(
17 | alt.datum.job == 'Welder'
18 | )
19 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: uncertainties and trends
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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/line_with_last_value_labeled.py:
--------------------------------------------------------------------------------
1 | """
2 | Line Chart with Last Value Labeled
3 | ----------------------------------
4 | This chart shows a line chart with a label annotating the final value
5 | """
6 | # category: line charts
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | # Import example data
11 | source = data.stocks()
12 |
13 | # Create a common chart object
14 | chart = alt.Chart(source).transform_filter(
15 | alt.datum.symbol != "IBM" # A reducation of the dataset to clarify our example. Not required.
16 | ).encode(
17 | alt.Color("symbol").legend(None)
18 | )
19 |
20 | # Draw the line
21 | line = chart.mark_line().encode(
22 | x="date:T",
23 | y="price:Q"
24 | )
25 |
26 | # Use the `argmax` aggregate to limit the dataset to the final value
27 | label = chart.encode(
28 | x='max(date):T',
29 | y=alt.Y('price:Q').aggregate(argmax='date'),
30 | text='symbol'
31 | )
32 |
33 | # Create a text label
34 | text = label.mark_text(align='left', dx=4)
35 |
36 | # Create a circle annotation
37 | circle = label.mark_circle()
38 |
39 | # Draw the chart with all the layers combined
40 | line + circle + text
41 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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('sum(people)').scale(type="log")
15 | )
16 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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(zero=False),
14 | alt.Y('sepalWidth').scale(zero=False, padding=1),
15 | color='species',
16 | size='petalWidth'
17 | )
18 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/multiline_highlight.py:
--------------------------------------------------------------------------------
1 | """
2 | Multi-Line Highlight
3 | ====================
4 | This multi-line chart uses an invisible Voronoi tessellation to handle pointerover 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_point(on='pointerover', fields=['symbol'], nearest=True)
16 |
17 | base = alt.Chart(source).encode(
18 | x='date:T',
19 | y='price:Q',
20 | color='symbol:N'
21 | )
22 |
23 | points = base.mark_circle().encode(
24 | opacity=alt.value(0)
25 | ).add_params(
26 | highlight
27 | ).properties(
28 | width=600
29 | )
30 |
31 | lines = base.mark_line().encode(
32 | size=alt.when(~highlight).then(alt.value(1)).otherwise(alt.value(3))
33 | )
34 |
35 | points + lines
36 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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.ThetaDatum((5 / 8) * np.pi).scale(None),
15 | theta2=alt.Theta2Datum((19 / 8) * np.pi),
16 | radius=alt.RadiusDatum(100).scale(None),
17 | )
18 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/parallel_coordinates.py:
--------------------------------------------------------------------------------
1 | """
2 | Parallel Coordinates
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: advanced calculations
12 |
13 | import altair as alt
14 | from vega_datasets import data
15 |
16 | source = data.iris()
17 |
18 | alt.Chart(source, width=500).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 | )
29 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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({
12 | 'Activity': ['Sleeping', 'Eating', 'TV', 'Work', 'Exercise'],
13 | 'Time': [8, 2, 4, 8, 2]
14 | })
15 |
16 | alt.Chart(source).transform_joinaggregate(
17 | TotalTime='sum(Time)',
18 | ).transform_calculate(
19 | PercentOfTotal="datum.Time / datum.TotalTime"
20 | ).mark_bar().encode(
21 | alt.X('PercentOfTotal:Q').axis(format='.0%'),
22 | y='Activity:N'
23 | )
24 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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="value",
17 | color="category"
18 | )
19 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 | alt.Theta("value:Q").stack(True),
19 | alt.Color("category:N").legend(None)
20 | )
21 |
22 | pie = base.mark_arc(outerRadius=120)
23 | text = base.mark_text(radius=140, size=20).encode(text="category:N")
24 |
25 | pie + text
26 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: uncertainties and trends
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"),
24 | alt.Y("y")
25 | )
26 |
27 | polynomial_fit = [
28 | base.transform_regression(
29 | "x", "y", method="poly", order=order, as_=["x", str(order)]
30 | )
31 | .mark_line()
32 | .transform_fold([str(order)], as_=["degree", "y"])
33 | .encode(alt.Color("degree:N"))
34 | for order in degree_list
35 | ]
36 |
37 | alt.layer(base, *polynomial_fit)
38 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/pyramid.py:
--------------------------------------------------------------------------------
1 | """
2 | Pyramid Pie Chart
3 | -----------------
4 | Altair reproduction of http://robslink.com/SAS/democd91/pyramid_pie.htm
5 | """
6 | # category: case studies
7 | import altair as alt
8 | import pandas as pd
9 |
10 | category = ['Sky', 'Shady side of a pyramid', 'Sunny side of a pyramid']
11 | color = ["#416D9D", "#674028", "#DEAC58"]
12 | df = pd.DataFrame({'category': category, 'value': [75, 10, 15]})
13 |
14 | alt.Chart(df, width=150, height=150).mark_arc(outerRadius=80).encode(
15 | alt.Theta('value:Q').scale(range=[2.356, 8.639]),
16 | alt.Color('category:N')
17 | .title(None)
18 | .scale(domain=category, range=color)
19 | .legend(orient='none', legendX=160, legendY=50),
20 | order='value:Q'
21 | ).configure_view(
22 | strokeOpacity=0
23 | )
24 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 | alt.Theta("values:Q").stack(True),
17 | alt.Radius("values").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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/ranged_dot_plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Ranged Dot Plot
3 | ---------------
4 | This example shows a ranged dot plot to convey changing life expectancy for the five most populous countries (between 1955 and 2000).
5 | """
6 | # category: advanced calculations
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | source = data.countries.url
11 |
12 | chart = (
13 | alt.Chart(source)
14 | .encode(x="life_expect:Q", y="country:N")
15 | .transform_filter(
16 | alt.FieldOneOfPredicate(
17 | field="country",
18 | oneOf=["China", "India", "United States", "Indonesia", "Brazil"],
19 | )
20 | )
21 | .transform_filter(alt.FieldOneOfPredicate(field="year", oneOf=[1955, 2000]))
22 | )
23 |
24 | line = chart.mark_line(color="#db646f").encode(detail="country:N")
25 |
26 | # Add points for life expectancy in 1955 & 2000
27 | color = alt.Color("year:O").scale(domain=[1955, 2000], range=["#e6959c", "#911a24"])
28 | points = (
29 | chart.mark_point(
30 | size=100,
31 | opacity=1,
32 | filled=True,
33 | )
34 | .encode(color=color)
35 | .interactive()
36 | )
37 |
38 | (line + points)
39 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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').title('Max Temp')
28 | )
29 |
30 | points + line
31 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: uncertainties and trends
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 | alt.X('x').scale(domain=(0, 6)),
33 | alt.Y('y').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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: advanced calculations
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('variety').sort(
19 | field='yield',
20 | op='mean',
21 | order='descending'
22 | )
23 | ).properties(
24 | width=400,
25 | height=250
26 | )
27 |
28 | error_bars = points.mark_rule().encode(
29 | x='ci0(yield)',
30 | x2='ci1(yield)',
31 | )
32 |
33 | points + error_bars
34 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: advanced calculations
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')
31 | .title('')
32 | .axis(ticks=False, labels=False, grid=False),
33 | alt.Y('stem:N')
34 | .title('')
35 | .axis(tickSize=0),
36 | text='leaf:N',
37 | ).configure_axis(
38 | labelFontSize=20
39 | ).configure_text(
40 | fontSize=20
41 | )
42 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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').axis(format='%Y', domain=False, tickSize=0),
14 | alt.Y('sum(count):Q').stack('center').axis(None),
15 | alt.Color('series:N').scale(scheme='category20b')
16 | ).interactive()
17 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: advanced calculations
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 | alt.X('Title:N').sort('-y'),
19 | alt.Y('IMDB_Rating:Q'),
20 | 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 | )
28 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/top_k_with_others.py:
--------------------------------------------------------------------------------
1 | """
2 | Top-K Plot with Others
3 | ----------------------
4 | This example shows how to use aggregate, window, and calculate transformations
5 | to display the top-k directors by average worldwide gross while grouping the
6 | remaining directors as 'All Others'.
7 | """
8 | # category: advanced calculations
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 | alt.X("aggregate_gross:Q").aggregate("mean").title(None),
16 | alt.Y("ranked_director:N")
17 | .sort(op="mean", field="aggregate_gross", order="descending")
18 | .title(None)
19 | ).transform_aggregate(
20 | aggregate_gross='mean(Worldwide_Gross)',
21 | groupby=["Director"],
22 | ).transform_window(
23 | rank='row_number()',
24 | sort=[alt.SortField("aggregate_gross", order="descending")],
25 | ).transform_calculate(
26 | ranked_director="datum.rank < 10 ? datum.Director : 'All Others'"
27 | ).properties(
28 | title="Top Directors by Average Worldwide Gross",
29 | )
30 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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('sum(people):Q').title('Population').axis(format='~s'),
16 | facet=alt.Facet('year:O').columns(5),
17 | ).properties(
18 | title='US Age Distribution By Year',
19 | width=90,
20 | height=80
21 | )
22 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/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: distributions
7 | import altair as alt
8 | from vega_datasets import data
9 |
10 | alt.Chart(data.cars(), width=100).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 | alt.X('density:Q')
17 | .stack('center')
18 | .impute(None)
19 | .title(None)
20 | .axis(labels=False, values=[0], grid=False, ticks=True),
21 | alt.Y('Miles_per_Gallon:Q'),
22 | alt.Color('Origin:N'),
23 | alt.Column('Origin:N')
24 | .spacing(0)
25 | .header(titleOrient='bottom', labelOrient='bottom', labelPadding=0)
26 | ).configure_view(
27 | stroke=None
28 | )
29 |
--------------------------------------------------------------------------------
/tests/examples_methods_syntax/wilkinson-dot-plot.py:
--------------------------------------------------------------------------------
1 | """
2 | Wilkinson Dot Plot
3 | ------------------
4 | An example of a `Wilkinson Dot Plot `_
5 | """
6 | # category: advanced calculations
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, height=100).mark_circle(opacity=1).transform_window(
20 | id='rank()',
21 | groupby=['data']
22 | ).encode(
23 | alt.X('data:O'),
24 | alt.Y('id:O').axis(None).sort('descending')
25 | )
26 |
--------------------------------------------------------------------------------
/tests/expr/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/tests/expr/__init__.py
--------------------------------------------------------------------------------
/tests/test_toplevel.py:
--------------------------------------------------------------------------------
1 | import altair as alt
2 | from tools import update_init_file
3 |
4 |
5 | def test_completeness_of__all__():
6 | relevant_attributes = update_init_file.relevant_attributes(alt.__dict__)
7 |
8 | # If the assert statement fails below, there are probably either new objects
9 | # in the top-level Altair namespace or some were removed.
10 | # In that case, run `hatch run update-init-file` to update __all__
11 | assert alt.__all__ == relevant_attributes
12 |
--------------------------------------------------------------------------------
/tests/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/tests/utils/__init__.py
--------------------------------------------------------------------------------
/tests/utils/test_execeval.py:
--------------------------------------------------------------------------------
1 | from altair.utils.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 |
--------------------------------------------------------------------------------
/tests/utils/test_server.py:
--------------------------------------------------------------------------------
1 | """Test http server."""
2 |
3 | from altair.utils.server import MockServer, serve
4 | from tests import slow
5 |
6 |
7 | @slow
8 | def test_serve():
9 | html = "TitleContent
"
10 | serve(html, open_browser=False, http_server=MockServer)
11 |
--------------------------------------------------------------------------------
/tests/vegalite/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/tests/vegalite/__init__.py
--------------------------------------------------------------------------------
/tests/vegalite/v5/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/tests/vegalite/v5/__init__.py
--------------------------------------------------------------------------------
/tests/vegalite/v5/schema/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vega/altair/d1f4a1ef89006e5f6752ef1f6df4b7a509336fba/tests/vegalite/v5/schema/__init__.py
--------------------------------------------------------------------------------
/tests/vegalite/v5/test_alias.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | import altair.vegalite.v5 as alt
4 |
5 |
6 | def test_aliases():
7 | """Ensure that any aliases defined in `api.py` aren't colliding with names already defined in `core.py` or `channels.py`."""
8 | for alias in ["Bin", "Impute", "Title"]:
9 | # this test pass if the alias can resolve to its real name
10 | try:
11 | getattr(alt, alias)
12 | except AttributeError as err:
13 | msg = f"cannot resolve '{alias}':, {err}"
14 | raise AssertionError(msg) from err
15 |
16 | # this test fails if the alias match a colliding name in core
17 | with pytest.raises(AttributeError):
18 | getattr(alt.core, alias)
19 |
20 | # this test fails if the alias match a colliding name in channels
21 | with pytest.raises(AttributeError):
22 | getattr(alt.channels, alias)
23 |
--------------------------------------------------------------------------------
/tests/vegalite/v5/test_data.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | import pandas as pd
4 | import pytest
5 |
6 | from altair.vegalite.v5 import data as alt
7 |
8 |
9 | @pytest.fixture
10 | def sample_data():
11 | return pd.DataFrame({"x": range(10), "y": range(10)})
12 |
13 |
14 | def test_disable_max_rows(sample_data):
15 | with alt.data_transformers.enable("default", max_rows=5):
16 | # Ensure max rows error is raised.
17 | with pytest.raises(alt.MaxRowsError):
18 | alt.data_transformers.get()(sample_data)
19 |
20 | # Ensure that max rows error is properly disabled.
21 | with alt.data_transformers.disable_max_rows():
22 | alt.data_transformers.get()(sample_data)
23 |
24 | try:
25 | # Ensure that there is no TypeError for non-max_rows transformers.
26 | with (
27 | alt.data_transformers.enable("json"),
28 | alt.data_transformers.disable_max_rows(),
29 | ):
30 | jsonfile = alt.data_transformers.get()(sample_data)
31 | except TypeError:
32 | jsonfile = {}
33 | finally:
34 | if jsonfile:
35 | Path(jsonfile["url"]).unlink()
36 |
--------------------------------------------------------------------------------
/tests/vegalite/v5/test_layer_props.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | import altair.vegalite.v5 as alt
4 |
5 |
6 | def test_layer_props():
7 | """Beginning in Vega-Lite v5, the properties "height" and "width" were no longer allowed in a subchart within a LayerChart. We check here that these are moved to the top level by Altair."""
8 | base = alt.Chart().mark_point()
9 |
10 | # Allowed
11 | base.properties(width=100) + base
12 | base.properties(width=100) + base.properties(height=200)
13 | base.properties(width=100) + base.properties(height=200, width=100)
14 |
15 | # Not allowed
16 | with pytest.raises(ValueError, match="inconsistent"):
17 | base.properties(width=100) + base.properties(width=200)
18 |
19 | # Check that the resulting LayerChart has the correct properties.
20 | c = base.properties(width=100) + base.properties(height=200, width=100)
21 | assert isinstance(c, alt.LayerChart)
22 | assert c.width == 100
23 | assert c.height == 200
24 |
--------------------------------------------------------------------------------
/tools/__init__.py:
--------------------------------------------------------------------------------
1 | from tools import (
2 | fs,
3 | generate_api_docs,
4 | generate_schema_wrapper,
5 | markup,
6 | schemapi,
7 | update_init_file,
8 | versioning,
9 | )
10 |
11 | __all__ = [
12 | "fs",
13 | "generate_api_docs",
14 | "generate_schema_wrapper",
15 | "markup",
16 | "schemapi",
17 | "update_init_file",
18 | "versioning",
19 | ]
20 |
--------------------------------------------------------------------------------
/tools/schemapi/__init__.py:
--------------------------------------------------------------------------------
1 | """schemapi: tools for generating Python APIs from JSON schemas."""
2 |
3 | from tools.schemapi import codegen, utils
4 | from tools.schemapi.codegen import (
5 | CodeSnippet,
6 | arg_invalid_kwds,
7 | arg_kwds,
8 | arg_required_kwds,
9 | )
10 | from tools.schemapi.schemapi import SchemaBase, Undefined
11 | from tools.schemapi.utils import OneOrSeq, SchemaInfo
12 | from tools.vega_expr import write_expr_module
13 |
14 | __all__ = [
15 | "CodeSnippet",
16 | "OneOrSeq",
17 | "SchemaBase",
18 | "SchemaInfo",
19 | "Undefined",
20 | "arg_invalid_kwds",
21 | "arg_kwds",
22 | "arg_required_kwds",
23 | "codegen",
24 | "utils",
25 | "write_expr_module",
26 | ]
27 |
--------------------------------------------------------------------------------