Shared axis labels with independent scale

Viewed 724

When facet/concat-ing charts, I would like the axis labels to be shared (so only 1 label per column/row, here: Horsepower), but the scale to be independent. Is this possible?

I thought a combination of resolve_axis and resolve_scale would be the way to go, as the title is a part of Axis, but I didn't get it to work.

I'm also wondering what resolve_axis actually does different than resolve_scale, anyone has an example?

base = alt.Chart(source).mark_circle().encode(
    x=alt.X('Horsepower:Q',),
    y=alt.Y('Miles_per_Gallon:Q'),
    color='Origin:N',
    row=alt.Row('Origin:N'),
).properties(
    width=200, height=100
)

base.resolve_axis(
    x='shared' # doesn't do anything obvious
).resolve_scale(
    x='independent'
)

Open the Chart in the Vega Editor

plot

2 Answers

I found a hacky way to do this, by misusing the facet header:

base = alt.Chart(source).mark_circle(size=60).encode(
    x=alt.X('Horsepower:Q',),
    y=alt.Y('Miles_per_Gallon:Q',
           axis=alt.Axis(title=''),),
    color='Origin:N',
    column=alt.Column('Origin:N', header=alt.Header(title='Miles_per_Gallon')),
).properties(
    width=200, height=200
).configure_header(
    labelExpr="['Origin',datum.value]",
    titleOrient='left'
)
display(base.resolve_scale(y='shared'))
display(base.resolve_scale(y='independent'))

plot1 plot2

I don't know of any way to do what you're hoping for (independent scales with only a single outer axis title) via scale and guide resolution.

As to your question of the difference between resolve_scale and resolve_axis, an example may help.

Here's a chart with independent y scale:

import altair as alt
from vega_datasets import data
source = data.cars()

base = alt.Chart(source).mark_circle().encode(
    x=alt.X('Horsepower:Q',),
    y=alt.Y('Miles_per_Gallon:Q'),
    color='Origin:N',
    column=alt.Column('Origin:N'),
).properties(
    width=150, height=150
)

base.resolve_scale(
    y='independent'
)

enter image description here

And here's one with independent y axis:

base.resolve_axis(
    y='independent'
)

enter image description here

In both cases, each chart gets its own axis (because independent scales imply independent axes), but only with an independent scale do the axes scales differ from each other.

Related