Search code examples
pythonchartsscrollscalingaltair

Python Altair - Bar Chart - Scale Binding


I would like to combine two examples from Altair documentation to gain the ability to scroll through a bar-chart vertically. One use case of this would be a Gantt chart.

Presently I only gain the ability to scroll horizontally, with the chart content being squashed to the height property that I define:

import altair as alt
from vega_datasets import data

source = data.wheat()

bars = alt.Chart(source).mark_bar().encode(
    x='wheat:Q',
    y="year:O"
)

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'
)

selection = alt.selection_interval(bind='scales')
(bars + text).properties(height=300).add_selection(
    selection
)

How can I configure the chart to retain the original proportions and allow scrolling within the defined height?

Thank you!


Solution

  • Categorical encodings, such as ordinal (":O") and nominal (":N") cannot have scale-bound selections. To make the vertical axis interactive, you should make the y encoding quantitative. For example:

    bars = alt.Chart(source).mark_bar(orient='horizontal').encode(
        x='wheat:Q',
        y='year:Q',
    )