Search code examples
pythonaltair

Altair Bar Chart - how to show missing categories


I have this chart below, which looks great. Category '2' on the X-axis has however been omitted because there is no data available in the dataframe.

What is the best way to go about this in Altair? I would like the '2' leadtime to show as an empty space/column (same width as a column).

enter image description here

import altair as alt
alt.Chart(data).mark_bar().encode(
    x='leadtime:O',
    y='value',
    color='category'
)

Data

leadtime    category    value
1   cat1    1
1   cat2    1
1   cat3    1
1   cat4    2
1   cat5    2
1   cat6    0.5
1   cat7    3
3   cat1    2
3   cat2    3
3   cat3    2
3   cat4    4
3   cat5    5
3   cat6    0.5
3   cat7    6
4   cat1    2
4   cat2    4
4   cat3    2
4   cat4    7
4   cat5    8
4   cat6    8
4   cat7    3

Solution

  • You can do this in two ways, either using an impute transform in y:

    alt.Chart(data).mark_bar().encode(
        x='leadtime:O',
        color='category',
        y=alt.Y('value',
          impute=alt.ImputeParams(
            value=0,
            keyvals=[1, 2, 3, 4]
          )
        ),
    )
    

    enter image description here

    or setting an explicit scale domain in x:

    alt.Chart(data).mark_bar().encode(
        x=alt.X('leadtime:O', scale=alt.Scale(domain=[1, 2, 3, 4])),
        y='value',
        color='category',
    )
    

    enter image description here