altair
altair copied to clipboard
Make alt.Facet arguments accept column-name or vectorised inputs
Suggestion
Is there a nice way to customise properties of faceted (or repeated) plots using other variables in the dataframe besides the faceting one? Assigning other parameters as vectors or dataframe column names instead of having to manually assemble the plots in a loop would be very convenient and intuitive.
Simple example using code from the faceting documentation: setting the sizes and colours of subplot titles
import altair as alt
from vega_datasets import data
iris = data.iris.url
alt.Chart(iris).mark_point().encode(
x = 'petalLength:Q',
y = 'petalWidth:Q',
color = 'species:N'
).properties(
width = 180,
height = 180
).facet(
alt.Facet('species:N',
# Having arguments accept column names or iterables of the same length would be very intuitive
header = alt.Header(labelFontSize = 'font_size_column:Q', labelColor = ['red', 'green', 'blue']),
title = 'titles_column:N'), # or similar
# ...
# Currently accepting only scalars
# header = alt.Header(labelFontSize = 17, labelColor = 'red'), # e.g. specify individual font sizes and colours for the headers
# title = 'Not the subplot titles'), # e.g. specify individual titles
columns = 4,
title = 'Not the subplot titles either'
)
Current solution
The above example can be achieved simply enough by manually assembling the subplots, but the situation can get complicated for more elaborate compound charts and datasets, and having intuitive options in the facet block would be very convenient.
import altair as alt
from vega_datasets import data
iris = data.iris.url
base = alt.Chart(iris).mark_point().encode(
x = 'petalLength:Q',
y = 'petalWidth:Q',
color = 'species:N'
).properties(
width=160,
height=160
)
chart = alt.hconcat()
for species, title_colour in zip(['setosa', 'versicolor', 'virginica'], ['red', 'green', 'blue']):
chart |= base.transform_filter(alt.datum.species == species).properties(
title = alt.Title(species, fontSize = 17, color = title_colour))
chart
I don't believe it is possible currently. Those parameters only accept a string, not a reference to a column. This functionality would need to be added on the VegaLite level before it can become available in Altair. There are a few PRs around supporting ExpRef more generally (which would allow referencing fields). I am not sure they would also apply to the specific faceting parameters you are referring to, but I will link them here in case https://github.com/vega/vega-lite/pull/7438 and https://github.com/vega/vega-lite/pull/9301. I usually do something similar to your workaround when I need similar functionality at the moment.
Closing as not planned