[Python] Altair chart empty by dropdown when other chart is displayed

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I want to have two different charts, where in the first I can choose an artist in a legend and in the second chart I want to have a dropdown, that filters a year. In my database I have artists, sales and years (for published albums). The charts work fine by itself, but if I want to show both with a vertical concatenation I get a problem. The first chart works as expected but the second graph is completely empty on selecting a year.

    import altair as alt
    import pandas as pd

    # Sample Data
    top = pd.DataFrame({
    'Artist': ['Artist1', 'Artist2', 'Artist3', 'Artist1', 'Artist2', 'Artist3'],
    'Sales': [100, 200, 300, 150, 250, 350],
    'Year': ['2020', '2020', '2020', '2021', '2021', '2021'],
    })

    # Selection for the legend
    select_artist_legend = alt.selection_point(fields=["Artist"], bind="legend")

    # First plot (cumulative sales over years)
    line = alt.Chart(top).transform_window(
    cumulative_sales='sum(Sales)',
    sort=[{'field': 'Year'}],
    groupby=['Artist']
    ).mark_line().encode(
    alt.X("Year:T"),
    alt.Y("cumulative_sales:Q"),
    alt.Color("Artist:N"),
    opacity=alt.condition(select_artist_legend, alt.value(1.0), alt.value(0.1))
    ).add_params(select_artist_legend)

    # Dropdown selection for the year
    year_dd = alt.binding_select(options=sorted(top.Year.unique()), name="Year")
    year_select = alt.selection_point(fields=["Year"], bind=year_dd, name='year_select')

    # Third plot (sales by artist for selected year)
    bar = alt.Chart(top).mark_bar().encode(
    alt.X("Artist:N"),
    alt.Y("Sales:Q"),
    alt.Color("Artist:N")
    ).add_params(year_select).transform_filter(year_select)

    # Combine the charts
    combined_chart = line & bar
    combined_chart


    Note: I'm using VS Code and Python Notebooks

    I tried debugging and trying to separate the two charts more, didn't seem to help. I also tried stacking bar twice instead of stacking line and bar, but there everything works, so stacking by itself didn't seem to be the problem.

    Continue reading...

Compartilhe esta Página