### Basic HTML Template for Embedding Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst An example of a basic HTML template that can be used to embed an Altair/Vega-Lite chart. ```html
``` -------------------------------- ### Shorthand Syntax for Quantitative Data Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Illustrates the shorthand syntax for specifying a quantitative data type in an encoding channel. ```python y = alt.Y('average(b):Q') print(y.to_json()) ``` -------------------------------- ### Saving a Chart to an HTML File Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Provides an example of how to save an Altair chart to a stand-alone HTML file. ```python chart = alt.Chart(data).mark_bar().encode( x='a', y='average(b)', ) chart.save('chart.html') ``` -------------------------------- ### Geo Line Example Setup Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/line.rst Setup for drawing lines through geographic points by mapping coordinate data to longitude and latitude channels with a projection. ```python import altair as alt from altair.datasets import data import pandas as pd airports = data.airports.url flights_airport = data.flights_airport.url ``` -------------------------------- ### Inspecting JSON Output Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Shows how to use the `to_json` method to inspect the Vega-Lite JSON specification generated by Altair. ```python chart = alt.Chart(data).mark_bar().encode( x='a', y='average(b)', ) print(chart.to_json()) ``` -------------------------------- ### Install Altair with all optional dependencies using pip Source: https://github.com/vega/altair/blob/main/doc/getting_started/installation.rst Installs Altair along with all its optional dependencies. ```bash pip install "altair[all]" ``` -------------------------------- ### Basic Point Mark Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This example shows how to create a basic point mark for the chart object without specifying any encodings. ```python alt.Chart(data).mark_point() ``` -------------------------------- ### Installing altair_data_server Source: https://github.com/vega/altair/blob/main/doc/user_guide/large_datasets.rst Install the altair_data_server package using pip. ```none pip install altair_data_server ``` -------------------------------- ### Explicit Channel Specification in Chart Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Shows how to use the verbose channel specification directly within an Altair chart. ```python alt.Chart(data).mark_bar().encode( alt.Y('a', type='nominal'), alt.X('b', type='quantitative', aggregate='average') ) ``` -------------------------------- ### Install vega via pip Source: https://github.com/vega/altair/blob/main/doc/user_guide/display_frontends.rst Installation command for the vega package using pip. ```bash $ pip install vega ``` -------------------------------- ### Default Theme Configuration Source: https://github.com/vega/altair/blob/main/doc/user_guide/customization.rst Example showing how to get and inspect the default theme configuration in Altair. ```python import altair as alt default = alt.theme.get() default() ``` -------------------------------- ### Verbose Channel Specification Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Demonstrates the more verbose way of specifying channel parameters by name, which is useful for advanced configurations. ```python y = alt.Y(field='b', type='quantitative', aggregate='average') print(y.to_json()) ``` -------------------------------- ### Install VegaFusion Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/index.rst Instructions to install VegaFusion with embed extras enabled. ```none pip install "vegafusion[embed]" ``` -------------------------------- ### Install Altair in Pyodide environments using micropip Source: https://github.com/vega/altair/blob/main/doc/getting_started/installation.rst Installs Altair in a Pyodide-based environment using the micropip package manager. ```python import micropip await micropip.install("altair") ``` -------------------------------- ### Install Python with uv Source: https://github.com/vega/altair/blob/main/CONTRIBUTING.md Command to install a specific Python version using uv. ```cmd uv python install 3.12 ``` -------------------------------- ### Horizontal Bar Chart Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Demonstrates how to create a horizontal bar chart by swapping the x and y encoding channels. ```python alt.Chart(data).mark_bar().encode( y='a', x='average(b)' ) ``` -------------------------------- ### Header Configuration Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/configuration.rst This example demonstrates how to configure the appearance of chart headers, including title and label colors and font sizes. ```python import altair as alt from altair.datasets import data source = data.cars.url chart = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N', column='Origin:N' ).properties( width=180, height=180 ) chart.configure_header( titleColor='green', titleFontSize=14, labelColor='red', labelFontSize=14 ) ``` -------------------------------- ### Bar Mark with Aggregation Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This example demonstrates using bar marks to visualize the aggregated average of the 'b' column for each category in 'a'. ```python alt.Chart(data).mark_bar().encode( x='a', y='average(b)' ) ``` -------------------------------- ### Install Altair with all optional dependencies using conda Source: https://github.com/vega/altair/blob/main/doc/getting_started/installation.rst Installs Altair along with all its optional dependencies using the conda package manager. ```bash conda install -c conda-forge altair-all ``` -------------------------------- ### Install vega via conda Source: https://github.com/vega/altair/blob/main/doc/user_guide/display_frontends.rst Installation command for the vega package using conda. ```bash $ conda install vega --channel conda-forge ``` -------------------------------- ### Install a specific version of Altair in Pyodide environments Source: https://github.com/vega/altair/blob/main/doc/getting_started/installation.rst Installs a specific version of Altair in a Pyodide-based environment. ```python await micropip.install("altair==6.1.0") ``` -------------------------------- ### Install VegaFusion with pip Source: https://github.com/vega/altair/blob/main/doc/user_guide/large_datasets.rst Command to install VegaFusion using pip. ```none pip install vegafusion ``` -------------------------------- ### Customizing Mark Color and Axis Titles Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst Demonstrates how to customize the mark color and axis titles using Altair's API. ```python alt.Chart(data).mark_bar(color='firebrick').encode( alt.Y('a').title('category'), alt.X('average(b)').title('avg(b) by category') ) ``` -------------------------------- ### View Configuration Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/configuration.rst This example shows how to configure the view of the chart, controlling properties like continuous height and width, stroke width, fill color, and stroke color. ```python import altair as alt from altair.datasets import data source = data.cars.url chart = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', ) chart.configure_view( continuousHeight=200, continuousWidth=200, strokeWidth=4, fill='#FFEEDD', stroke='red', ) ``` -------------------------------- ### Example Data Loading Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/lookup.rst Loads the example people and groups data for demonstration. ```python from altair.datasets import data people = data.lookup_people() groups = data.lookup_groups() ``` -------------------------------- ### Index selection example setup Source: https://github.com/vega/altair/blob/main/doc/user_guide/interactions/jupyter_chart.rst This code sets up a point selection named 'point' without specific fields or encodings, which is suitable for index-based selections where the selection value will be a list of row indices. ```python import altair as alt from altair.datasets import data source = data.cars() brush = alt.selection_point(name="point") ``` -------------------------------- ### Install Altair with save dependencies using pip Source: https://github.com/vega/altair/blob/main/doc/getting_started/installation.rst Installs Altair with only the dependencies necessary for saving charts to offline HTML files or PNG/SVG/PDF formats. ```bash pip install "altair[save]" ``` -------------------------------- ### Title Configuration Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/configuration.rst This example demonstrates how to configure the chart title with specific font size, font family, anchor, and color. ```python import altair as alt from altair.datasets import data source = data.cars.url chart = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', ).properties( title='Cars Data' ) chart.configure_title( fontSize=20, font='Courier', anchor='start', color='gray' ) ``` -------------------------------- ### Create example image arrays Source: https://github.com/vega/altair/blob/main/doc/case_studies/numpy-tooltip-images.rst This code snippet generates example image arrays with blobs of different shapes and sizes, and measures their areas. ```python import numpy as np import pandas as pd from scipy import ndimage as ndi rng = np.random.default_rng([ord(c) for c in 'altair']) n_rows = 200 def create_blobs(blob_shape, img_width=96, n_dim=2, sizes=[0.05, 0.1, 0.15]): """Helper function to create blobs in the images""" shape = tuple([img_width] * n_dim) mask = np.zeros(shape) points = (img_width * rng.random(n_dim)).astype(int) mask[tuple(indices for indices in points)] = 1 if blob_shape == 'circle': im = ndi.gaussian_filter(mask, sigma=rng.choice(sizes) * img_width) elif blob_shape == 'square': im = ndi.uniform_filter(mask, size=rng.choice(sizes) * img_width, mode='constant') * rng.normal(4, size=(img_width, img_width)) return im / im.max() df = pd.DataFrame({ 'image1': [create_blobs('circle') for _ in range(n_rows)], 'image2': [create_blobs('square', sizes=[0.3, 0.4, 0.5]) for _ in range(n_rows)], 'group': rng.choice(['a', 'b', 'c'], size=n_rows) }) # Compute the area as the proportion of pixels above a threshold df[['image1_area', 'image2_area']] = df[['image1', 'image2']].map(lambda x: (x > 0.4).mean()) df ``` -------------------------------- ### Create a Pandas DataFrame Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This snippet shows how to create a simple pandas DataFrame with categorical and numerical columns, which is the fundamental data structure for Altair visualizations. ```python import pandas as pd data = pd.DataFrame({'a': list('CCCDDDEEE'), 'b': [2, 7, 4, 1, 2, 6, 8, 4, 7]}) ``` -------------------------------- ### Example Layered Chart Source: https://github.com/vega/altair/blob/main/doc/user_guide/data_transformers.rst A simple layered chart example using Altair and pandas. ```python import altair as alt import pandas as pd df = pd.DataFrame({'x': range(5), 'y': [1, 3, 4, 3, 5]}) line = alt.Chart(df).mark_line().encode(x='x', y='y') points = alt.Chart(df).mark_point().encode(x='x', y='y') chart = line + points ``` -------------------------------- ### Install JupyterLab Source: https://github.com/vega/altair/wiki/Display-Troubleshooting Instructions for installing or updating JupyterLab using conda. ```bash $ conda install jupyterlab # if you don't have it installed $ conda update jupyterlab ``` -------------------------------- ### Install Vega3 JupyterLab Extension Source: https://github.com/vega/altair/wiki/Display-Troubleshooting Command to install the necessary JupyterLab extension for Vega-3 compatibility. ```bash jupyter labextension install @jupyterlab/vega3-extension ``` -------------------------------- ### Install JupyterLab Vega Extension Source: https://github.com/vega/altair/blob/main/doc/user_guide/display_frontends.rst Command to install the vega labextension for offline rendering in JupyterLab. ```bash jupyter labextension install @jupyterlab/vega5-extension ``` -------------------------------- ### Shorthand Encoding Examples Source: https://github.com/vega/altair/blob/main/doc/user_guide/encodings/index.rst Examples demonstrating the shorthand syntax for various encodings, including quantitative types and aggregations. ```python x='name:Q' alt.X('name', type='quantitative') ``` ```python x='sum(name)' alt.X('name', aggregate='sum') ``` ```python x='sum(name):Q' alt.X('name', aggregate='sum', type='quantitative') ``` ```python x='count():Q' alt.X(aggregate='count', type='quantitative') ``` -------------------------------- ### Install VegaFusion with conda Source: https://github.com/vega/altair/blob/main/doc/user_guide/large_datasets.rst Command to install VegaFusion using conda. ```none conda install -c conda-forge vegafusion vl-convert-python ``` -------------------------------- ### Interactive Scatter Plot Example Source: https://github.com/vega/altair/blob/main/doc/getting_started/overview.rst An example demonstrating how to use the Vega-Altair API to create an interactive scatter plot with linked data columns and visual encoding channels. ```python import altair as alt from altair.datasets import data cars = data.cars() alt.Chart(cars).mark_point().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive() ``` -------------------------------- ### Example of using the sample transform Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/sample.rst This example demonstrates how to use the transform_sample method to create a chart using a random subset of 100 rows from the cars dataset, displayed alongside the full dataset. ```python import altair as alt from altair.datasets import data source = data.cars.url chart = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N' ).properties( width=200, height=200 ) chart | chart.transform_sample(100) ``` -------------------------------- ### Legend Configuration Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/configuration.rst This example shows how to customize the appearance of chart legends, including stroke color, fill color, padding, corner radius, and orientation. ```python import altair as alt from altair.datasets import data source = data.cars.url chart = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N' ) chart.configure_legend( strokeColor='gray', fillColor='#EEEEEE', padding=10, cornerRadius=10, orient='top-right' ) ``` -------------------------------- ### Build and Serve Documentation (Faster Build) Source: https://github.com/vega/altair/blob/main/CONTRIBUTING.md Commands to build and serve documentation faster by excluding autosummary and gallery generation. ```cmd uv run task doc-build -- --clean --no-autosummary --no-gallery uv run task doc-serve ``` -------------------------------- ### Cumulative Frequency Distribution Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/window.rst This example demonstrates how to create a cumulative frequency distribution using Altair's transform_aggregate and transform_window. It first counts movies by IMDB Rating and then calculates the cumulative count over a sorted window. ```python import altair as alt from altair.datasets import data alt.Chart(data.movies.url).transform_aggregate( count='count(*)', groupby=['IMDB Rating'] ).transform_window( sort=[{'field': 'IMDB Rating'}], frame=[None, 0], cumulative_count='sum(count)', ).mark_area().encode( x='IMDB Rating:Q', y='cumulative_count:Q', ) ``` -------------------------------- ### X and Y Axis Encoding Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This example demonstrates encoding both 'a' to the x-axis and 'b' to the y-axis, allowing for a scatter plot visualization. ```python alt.Chart(data).mark_point().encode( x='a', y='b' ) ``` -------------------------------- ### Example Dataset and Head Source: https://github.com/vega/altair/blob/main/doc/user_guide/times_and_dates.rst Loads the Seattle weather hourly normals dataset and displays the first few rows. ```python import altair as alt from altair.datasets import data temps = data.seattle_weather_hourly_normals() temps.head() ``` -------------------------------- ### Selection Predicate Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/filter.rst This example demonstrates using a multi-selection predicate to filter data. The top chart shows data selected by clicking or shift-clicking bars in the bottom chart. ```python import altair as alt from altair.datasets import data pop = data.population.url selection = alt.selection_point(fields=['year']) top = alt.Chart(width=600, height=200).mark_line().encode( x="age:O", y="sum(people):Q", color="year:O" ).transform_filter( selection ) color = alt.when(selection).then(alt.value("steelblue")).otherwise(alt.value("lightgray")) bottom = alt.Chart(width=600, height=100).mark_bar().encode( x="year:O", y="sum(people):Q", color=color ).add_params( selection ) alt.vconcat(top, bottom, data=pop) ``` -------------------------------- ### Build and Serve Documentation Source: https://github.com/vega/altair/blob/main/CONTRIBUTING.md Commands to clean, build, and serve the documentation locally. The `--clean` flag removes previously generated files. ```cmd uv run task doc-build -- --clean uv run task doc-serve ``` -------------------------------- ### X-axis Encoding Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This snippet illustrates encoding the 'a' column to the x-axis channel, which visually separates points by category. ```python alt.Chart(data).mark_point().encode( x='a', ) ``` -------------------------------- ### Initialize virtual environment with uv Source: https://github.com/vega/altair/blob/main/CONTRIBUTING.md Command to initialize a new virtual environment using uv. ```cmd cd altair/ uv venv -p 3.12 ``` -------------------------------- ### Aggregation with Average Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This snippet shows how to use aggregation within an encoding channel to display the average of the 'b' column for each category in 'a'. ```python alt.Chart(data).mark_point().encode( x='a', y='average(b)' ) ``` -------------------------------- ### Initialize a Chart Object Source: https://github.com/vega/altair/blob/main/doc/getting_started/starting.rst This snippet demonstrates how to create the fundamental Altair Chart object, which takes a pandas DataFrame as its primary argument. ```python import altair as alt chart = alt.Chart(data) ``` -------------------------------- ### Tutorial Outline Source: https://github.com/vega/altair/wiki/PyCon-Tutorial-Planning A basic outline of the topics to be covered in the tutorial. ```text 1. Install Altair 2. Create a bar chart 3. Marks 4. Encodings 5. Transformations 6. ... ``` -------------------------------- ### Build and Serve Documentation with Watch Mode Source: https://github.com/vega/altair/blob/main/CONTRIBUTING.md Command to build documentation with `--watch` flag for automatic rebuilding and refreshing upon file changes, optimized for local development. ```cmd uv run task doc-build -- --clean --no-autosummary --watch ``` -------------------------------- ### Initial Chart Setup Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/filter.rst Sets up the base Altair chart using population data. ```python import altair as alt from altair.datasets import data source = data.population.url chart = alt.Chart(source).mark_line().encode( x="age:O", y="sum(people):Q", color="year:O" ).properties( width=600, height=200 ) between_1950_60 = alt.FieldRangePredicate(field="year", range=[1950, 1960]) ``` -------------------------------- ### Setting Localization Options Source: https://github.com/vega/altair/blob/main/doc/user_guide/customization.rst Example of setting format and time format locales for chart rendering. ```python alt.renderers.set_embed_options(format_locale="it-IT", time_format_locale="it-IT") source = data.stocks.url chart = alt.Chart(source).mark_area().transform_filter('year(datum.date) == 2009').encode( x='date:T', y=alt.Y('price:Q', axis=alt.Axis(format="$.0f")), color='symbol:N' ) chart ``` -------------------------------- ### TOML Configuration for Vega Versions Source: https://github.com/vega/altair/blob/main/NOTES_FOR_MAINTAINERS.md Example TOML configuration for specifying Vega and related library versions. ```toml [tool.altair.vega] vega-datasets = "..." # https://github.com/vega/vega-datasets vega-embed = "..." # https://github.com/vega/vega-embed vega-lite = "..." # https://github.com/vega/vega-lite ``` -------------------------------- ### Build and publish documentation Source: https://github.com/vega/altair/blob/main/RELEASING.md Commands to build and publish the project's documentation. Requires write access to the altair-viz/altair-viz.github.io repository. ```bash uv run task doc-build -- --clean uv run task doc-publish ``` -------------------------------- ### Example DataFrame Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/joinaggregate.rst This code snippet demonstrates the creation of a sample pandas DataFrame used in the explanation. ```python import pandas as pd import numpy as np rand = np.random.RandomState(0) df = pd.DataFrame({ 'label': rand.choice(['A', 'B', 'C'], 10), 'value': rand.randn(10), }) ``` -------------------------------- ### Histogram Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/encodings/index.rst Example of creating a histogram by binning data and counting occurrences. ```python alt.Chart(cars).mark_bar().encode( alt.X('Horsepower').bin(), y='count()' # could also use alt.Y(aggregate='count', type='quantitative') ) ``` -------------------------------- ### Vertical Concatenation Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/compound_charts.rst An example demonstrating vertical concatenation of charts with interactive brushing. ```python import altair as alt from altair.datasets import data source = data.sp500.url brush = alt.selection_interval(encodings=['x']) base = alt.Chart(source).mark_area().encode( x = 'date:T', y = 'price:Q' ).properties( width=600, height=200 ) upper = base.encode(alt.X('date:T').scale(domain=brush)) lower = base.properties( height=60 ).add_params(brush) alt.vconcat(upper, lower) ``` -------------------------------- ### MaxRowsError Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/large_datasets.rst An example that triggers the MaxRowsError due to a dataset exceeding the default row limit. ```python import altair as alt import pandas as pd data = pd.DataFrame({"x": range(10000)}) alt.Chart(data).mark_point() ``` -------------------------------- ### Using Named Color Schemes Source: https://github.com/vega/altair/blob/main/doc/user_guide/customization.rst Demonstrates how to apply a named color scheme to a scale, using 'lightgreyred' as an example. ```python import altair as alt from altair.datasets import data cars = data.cars() alt.Chart(cars).mark_point().encode( x='Horsepower', y='Miles_per_Gallon', color=alt.Color('Acceleration').scale(scheme="lightgreyred") ) ``` -------------------------------- ### Publish to PyPI Source: https://github.com/vega/altair/blob/main/RELEASING.md Command to build a source distribution and wheel, and publish to PyPI. Requires appropriate permissions and UV_PUBLISH_TOKEN environment variable. ```bash uv run task publish ``` -------------------------------- ### JSONPATH Expression Tester Examples Source: https://github.com/vega/altair/wiki/Hackathon-Helper-Links Examples of JSONPATH expressions to query JSON schema definitions. ```jsonpath $.definitions[*].properties[*].description ``` ```jsonpath $.definitions[*].properties[*].['$ref'] ``` ```jsonpath $.definitions[*].properties.[?(@.anyOf)] ``` -------------------------------- ### FieldEqualPredicate Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/filter.rst This example uses FieldEqualPredicate to filter data, selecting only records where the 'year' field is equal to 2000. ```python import altair as alt from altair.datasets import data pop = data.population.url alt.Chart(pop).mark_line().encode( x='age:O', y='sum(people):Q', color='year:O' ).transform_filter( alt.FieldEqualPredicate(field='year', equal=2000) ) ``` -------------------------------- ### Example: Plotting Stock Prices Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/window.rst This code snippet demonstrates a basic Altair chart to plot stock prices over time. ```python import altair as alt from altair.datasets import data alt.Chart(data.stocks.url).mark_line().encode( x='date:T', y='price:Q', color='symbol:N', ) ``` -------------------------------- ### Fold Transform Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/fold.rst An example demonstrating the use of the fold transform to convert wide-form data to long-form data. ```python import numpy as np import pandas as pd import altair as alt rand = np.random.RandomState(0) data = pd.DataFrame({ 'date': pd.date_range('2019-01-01', freq='D', periods=30), 'A': rand.randn(30).cumsum(), 'B': rand.randn(30).cumsum(), 'C': rand.randn(30).cumsum(), }) alt.Chart(data).transform_fold( ['A', 'B', 'C'], ).mark_line().encode( x='date:T', y='value:Q', color='key:N' ) ``` -------------------------------- ### Run JupyterLab Source: https://github.com/vega/altair/wiki/Display-Troubleshooting Command to launch JupyterLab after installation. ```bash $ jupyter lab ``` -------------------------------- ### Heatmap Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/rect.rst An example of creating a heatmap using rect marks with discrete fields on x and y channels. ```python import altair as alt from altair.datasets import data source = data.seattle_weather() alt.Chart(source).mark_rect().encode( alt.X("date(date):O").axis(labelAngle=0, format="%e").title("Day"), alt.Y("month(date):O").title("Month"), alt.Color("max(temp_max):Q").title("Max Temp"), ) ``` -------------------------------- ### Defining and Registering a Custom Theme Source: https://github.com/vega/altair/blob/main/doc/user_guide/customization.rst Example of defining a custom theme ('black_marks') that sets all marks to black and registers/enables it. ```python import altair as alt from altair.datasets import data # define, register and enable theme @alt.theme.register("black_marks", enable=True) def black_marks() -> alt.theme.ThemeConfig: return { "config": { "view": {"continuousWidth": 300, "continuousHeight": 300}, "mark": {"color": "black", "fill": "black"}, } } # draw the chart cars = data.cars.url alt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q' ) ``` -------------------------------- ### Error Bar Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/errorband.rst This example shows the equivalent visualization using `mark_errorbar` for comparison with the error band. ```python import altair as alt from altair.datasets import data source = data.cars.url alt.Chart(source).mark_errorbar(extent="ci", ticks=True).encode( x="year(Year)", y=alt.Y( "Miles_per_Gallon:Q", scale=alt.Scale(zero=False), title="Miles per Gallon (95% CIs)", ), ) ``` -------------------------------- ### Basic Area Chart Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/area.rst An example of a basic area chart showing unemployment data over time. ```python import altair as alt from altair.datasets import data source = data.unemployment_across_industries.url alt.Chart(source).mark_area().encode( x="yearmonth(date):T", y="sum(count):Q", ).properties(width=300, height=200) ``` -------------------------------- ### Pivot Transform Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/pivot.rst An example demonstrating the pivot transform to convert long-form Olympic medals data to wide-form. ```python import altair as alt import pandas as pd df = pd.DataFrame.from_records([ {"country": "Norway", "type": "gold", "count": 14}, {"country": "Norway", "type": "silver", "count": 14}, {"country": "Norway", "type": "bronze", "count": 11}, {"country": "Germany", "type": "gold", "count": 14}, {"country": "Germany", "type": "silver", "count": 10}, {"country": "Germany", "type": "bronze", "count": 7}, {"country": "Canada", "type": "gold", "count": 11}, {"country": "Canada", "type": "silver", "count": 8}, {"country": "Canada", "type": "bronze", "count": 10} ]) alt.Chart(df).transform_pivot( 'type', groupby=['country'], value='count' ).mark_bar().encode( x='gold:Q', y='country:N', ) ``` -------------------------------- ### Quantile Plot Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/quantile.rst An example of creating a quantile plot of normally-distributed data using Altair's transform_quantile method. ```python import altair as alt import pandas as pd import numpy as np np.random.seed(42) df = pd.DataFrame({'x': np.random.randn(200)}) alt.Chart(df).transform_quantile( 'x', step=0.01 ).mark_point().encode( x='prob:Q', y='value:Q' ) ``` -------------------------------- ### Example Data Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/impute.rst This code snippet demonstrates how to create a sample DataFrame with missing values, which will be used in subsequent examples. ```python import numpy as np import pandas as pd data = pd.DataFrame({ 't': range(5), 'x': [2, np.nan, 3, 1, 3], 'y': [5, 7, 5, np.nan, 4] }).melt('t').dropna() data ``` -------------------------------- ### Streamgraph Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/area.rst An example of a streamgraph created by setting the stack baseline to 'center' and enabling interactivity for zooming and panning. ```python import altair as alt from altair.datasets import data # The actual code for the streamgraph example is missing in the provided content. # This is a placeholder based on the description. alt.Chart(data.unemployment_across_industries.url).mark_area(stack='center').encode( x='yearmonth(date):T', y='sum(count):Q', color='series:N' ).interactive() ``` -------------------------------- ### Run Test Suite Source: https://github.com/vega/altair/blob/main/NOTES_FOR_MAINTAINERS.md Command to run the Altair test suite. ```bash uv run task test ``` -------------------------------- ### Single Bar Chart Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/bar.rst A basic example of a single bar chart by mapping a quantitative field to the x-axis. ```python import altair as alt from altair import datum from altair.datasets import data source = data.population.url alt.Chart(source).mark_bar().encode( alt.X("sum(people):Q").title("Population") ).transform_filter( datum.year == 2000 ) ``` -------------------------------- ### Bar Mark Properties Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/marks/bar.rst This example demonstrates the use of cornerRadius property for bar marks, controlled by a slider. ```python import altair as alt import pandas as pd corner_slider = alt.binding_range(min=0, max=50, step=1) corner_var = alt.param(bind=corner_slider, value=0, name="cornerRadius") source = pd.DataFrame( { "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"], "b": [28, 55, 43, 91, 81, 53, 19, 87, 52], } ) alt.Chart(source).mark_bar(cornerRadius=corner_var).encode( x=alt.X("a:N").axis(labelAngle=0), y="b:Q", ).add_params(corner_var) ``` -------------------------------- ### Altair Join Aggregate Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/transform/joinaggregate.rst An example of using the join aggregate transform in Altair to compare normalized movie ratings. ```python import altair as alt from altair.datasets import data alt.Chart(data.movies.url).transform_filter( 'datum["IMDB Rating"] != null && datum["Rotten Tomatoes Rating"] != null' ).transform_joinaggregate( IMDB_mean='mean(IMDB Rating)', IMDB_std='stdev(IMDB Rating)', RT_mean='mean(Rotten Tomatoes Rating)', RT_std='stdev(Rotten Tomatoes Rating)' ).transform_calculate( IMDB_Deviation='(datum["IMDB Rating"] - datum.IMDB_mean) / datum.IMDB_std', Rotten_Tomatoes_Deviation='(datum["Rotten Tomatoes Rating"] - datum.RT_mean) / datum.RT_std' ).mark_point().encode( x='IMDB_Deviation:Q', y="Rotten_Tomatoes_Deviation:Q" ) ``` -------------------------------- ### Attribute-Based Syntax Example Source: https://github.com/vega/altair/blob/main/doc/user_guide/encodings/index.rst Shows the equivalent of the method-based syntax using the traditional attribute-based approach. ```python alt.Chart(cars).mark_point().encode( alt.X('Horsepower', axis=alt.Axis(tickMinStep=50)), alt.Y('Miles_per_Gallon', title="Miles per Gallon"), color='Origin', shape='Origin' ) ```