Search code examples
pythonaltair

Altair transfrom_density


I am trying to replicate this graph in Altair but for some reason is don't get any information on my chart, I can only see an empty chart.

enter image description here

link to data

My attempt:

alt.Chart(data).transform_density('age', as_=['age', 'density'],
).mark_area(color='survived').encode(
    x="age",
    y='density:Q',
)

Solution

  • color needs to be specified as an encoding when grouping by a variable, not as a mark parameter. In this case you also need to group the density calculation as in https://altair-viz.github.io/gallery/density_stack.html

    alt.Chart(data).transform_density(
        'age',
        as_=['age', 'density'],
        groupby=['survived']
    ).mark_area().encode(
        x="age",
        y='density:Q',
        color='survived:N'
    )
    

    enter image description here