Altair Hconcat - It it possible to configure different axes for charts in same HConCat?

Viewed 1322

I'm using streamlit to build a dashboard and I would like to present 2 charts one next to the other, using altair works well, the hconcat function allows me to do just that.

import altair as alt

df1 = pd.DataFrame({'metric':list('ab'),
             'value':[8,10]})

df2 = pd.DataFrame({'metric':list('xyz'),
             'value':[5,9,7]})

chart_1 = (alt.Chart(df1).mark_bar().encode(x='metric', y='value'))
chart_2 = (alt.Chart(df2).mark_bar().encode(x='metric', y='value'))

(chart_1 | chart_2)

Output

I would like for one chart to have Y axis on left side, and for the other chart Y axis on the right side but have not found a solution. The configuration can happen at the chart level:

chart_2 = (alt.Chart(df2).mark_bar().encode(x='metric', y='value')).configure_axisY(orient='right')

but then an exception is thrown when presenting using the hconcat func:

ValueError: Objects with "config" attribute cannot be used within HConcatChart. Consider defining the config attribute in the HConcatChart object instead.

Is there anyway to do this?

Thanks in advance

1 Answers

The config property can only be defined at the top level of a chart, as it essentially acts as a theme that applies to all components of the final chart.

If you want to set different axis properties for each subchart, the global configuration is not the place to do this; you can do it within the axis properties of each subchart. For example:

chart_1 = alt.Chart(df1).mark_bar().encode(
    x='metric',
    y=alt.Y('value', axis=alt.Axis(orient='left'))
)
chart_2 = alt.Chart(df2).mark_bar().encode(
    x='metric',
    y=alt.Y('value', axis=alt.Axis(orient='right'))
)

(chart_1 | chart_2)

enter image description here

Related