Faceting in Altair, a declarative statistical visualization library for Python, involves creating a series of plots that are partitioned by the values of a particular column. When you facet a scatter plot, you're essentially creating multiple scatter plots, each corresponding to a subset of your data. Here's how you can create a faceted scatter plot in Altair:
First, make sure you have Altair installed. You can install it via pip if it's not already in your environment:
pip install altair vega_datasets
Import Altair and load the data you want to use. For this example, I'll use a sample dataset from Altair's built-in datasets:
import altair as alt from vega_datasets import data # Load sample data cars = data.cars()
Use Altair's mark_point() for the scatter plot and facet() to create facets:
chart = alt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N' ).facet( column='Cylinders:O' ) chart
In this example:
mark_point() creates a scatter plot.encode() is used to specify what each axis and color will represent. Here, Horsepower and Miles_per_Gallon are on the x and y axes, respectively, and points are colored by Origin.facet(column='Cylinders:O') creates a separate plot for each number of cylinders.Here's the complete script:
import altair as alt from vega_datasets import data # Load sample data cars = data.cars() # Create a faceted scatter plot chart = alt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N' ).facet( column='Cylinders:O' ) chart
When you run this script in a Jupyter notebook or a similar environment that supports Altair rendering, you'll see a series of scatter plots, each showing data for cars with a different number of cylinders.
mark_*() function and the arguments to encode().chart.save('filename.png') or chart.save('filename.html'), respectively.edit deprecation-warning process canoe epl hangfire google-analytics imap proxy standard-library