Search code examples
pythonaltair

Specify plot title and facet title in Altair LayerChart


Using the iris dataset we can create a simple faceted chart:

import altair as alt
from vega_datasets import data
iris = data.iris.url

alt.Chart(iris, title='Main Title').mark_bar().encode(
    x='petalWidth:Q',
    y='count(petalLength):Q',
    color='species:N',
    facet=alt.Facet('species:N', title=None)
)

enter image description here

Here I can control both the main plot title and the title of the facets respectively.

Now let's say I want create the same chart, but add text annotations to each bar:

base = alt.Chart(iris).encode(
    x='petalWidth:Q',
    y='count(petalLength):Q',
    color='species:N',
    text='count(petalLength):Q'
)

c = base.mark_bar()
t = base.mark_text(dy=-6)

alt.layer(c, t).facet('species:N', title=None).properties(title='Main Title')

enter image description here

This time, there is the species title above the facets. How can I control both the main plot title and the facet title in this case?


Solution

  • Keyword arguments passed to the facet method are passed through to the alt.FacetChart chart that is created.

    Any keyword arguments you want passed to the facet encoding can be passed via an alt.Facet() wrapper, similar to other encodings.

    For example:

    alt.layer(c, t).facet(
        facet=alt.Facet('species:N', title=None),
        title='Main Title'
    )
    

    enter image description here