Search code examples
pythoncolorsaltairbinning

Altair binned color values - 7 colors


How would I add a third, fourth (ideally I would like to have 7 different) color bins to this histogram?

alt.Chart(X_train).transform_bin(
    'Creditworthiness_bin', 'Creditworthiness', bin=alt.Bin(step=10)
).transform_joinaggregate(
    count='count()', groupby=['Creditworthiness_bin']  
).mark_bar(orient='vertical').encode(
    alt.X('Creditworthiness_bin:Q', bin='binned'),
    alt.X2('Creditworthiness_bin_end'),
    alt.Y('count:Q'),
    color=alt.condition(
        alt.datum.Creditworthiness_bin_end <= 50,
        alt.value("steelblue"),  # The positive color
        alt.value("orange")  # The negative color
    )
)

enter image description here

This is a follow up to the original question asked here: Altair Color binned values

How can I add red, yellow, green, purple, etc. as options? The "_bin_end" line makes it seem like I can only set one threshold as opposed to several bins.


Solution

  • alt.Chart(X_train).mark_bar().encode(
        x = alt.X('Creditworthiness', bin=alt.Bin(extent=[0, 100], step=5)),
        y='count()',
        color=alt.Color('Creditworthiness:Q', title='Count',
                bin=alt.Bin(extent=[0, 100], step=10), 
                scale=alt.Scale(scheme='dark2')
            )
    )
    

    In the code above, the X-axis bin has steps=5, and the color bin has step=10. So two consecutive bars will have the same color.

    enter image description here