Search code examples
chartslinealtair

Altair Chart selected data to graph


I have a dataframe with multiple type-value pairs. Lets say it is:

dt = pd.DataFrame({'date': ['2022', '2023', '2024'], type':['t1', 't2', 't3'], 'value': [1, 2, 3]})

of cause, with much more data inside the dataframe. Standard way to show all 3 graphs would be:

    fig = alt.Chart(source).mark_line().encode(
        x=alt.X('date:T'),
        y=alt.Y('value:Q'),
        color=alt.Color('type:N')

it will show 3 lines of different types. What if I would like to show only 2 or only 1 type on the graph? I tried to set y axis as

y = alt.Y(['type1', 'type2'])

I suppose, it should be differently setup as that way is wrong. Is it a solution alternative to filtering the dataframe as source of data?


Solution

  • You could use transform_filter to filter the data in the chart rather than the dataframe ahead of time:

    import altair as alt
    from altair import datum
    
    from vega_datasets import data
    pop = data.population.url
    
    alt.Chart(pop).mark_area().encode(
        x='age:O',
        y='people:Q',
    ).transform_filter(
        (datum.year == 2000) & (datum.sex == 1)
    )
    

    Setting the domain of the color encoding to only include the options you want might also work.