Search code examples
pythonchartsvisualizationaltairvega

Centering the axis title between two concatenated Altair plots


I have an Altair plot that is a vertical concatenation of subplots. However, they share the y-axis title, and I would like to place this in the middle of the two plots.

For example, let's say I have this:

from sklearn.datasets import load_iris
import altair as alt
import pandas as pd

iris = load_iris()
_, y = load_iris(return_X_y = True)
df = pd.DataFrame(iris.data, columns=iris.feature_names).assign(label=y)

chart_a = alt.Chart(
    df[df.label == 0]
).mark_point().encode(
    x='sepal length (cm)',
    y='sepal width (cm)',
)
chart_b = alt.Chart(
    df[df.label == 1]
).mark_point().encode(
    x='sepal length (cm)',
    y='sepal width (cm)',
)

result = (chart_a & chart_b)

I'm not using faceting here because in my real example the scales are quite different. I have also annotated where I would like the shared y-axis label to be:

enter image description here.

I'm also hoping to remove the y-axis label from each of the subplots, but I think that's easier to do.

How can I implement this?


Solution

  • Just an FYI, you can still facet and have independent scales. Faceting makes it easier than concatenating charts together in this case. i.e.

    import altair as alt
    from vega_datasets import data
    
    iris = data.iris()
    
    
    
    alt.Chart(iris).mark_point().encode(
        alt.X('petalLength:Q'),
        alt.Y('petalWidth:Q', axis=alt.Axis(title=''))
    ).properties(
        width=180,
        height=180
    ).facet(
        row=alt.Row(field=alt.Field('species'),type='nominal',header=alt.Header( title='Sepal Width (cm)', labels=False, titleFontSize=25, titleColor='red'))
    ).resolve_scale(
        y='independent',
        x='independent',
    )
    

    enter image description here