Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altair - Bar Chart Domain Cropping Error when adding Color

I have a bar chart which shows percentage values for several languages.

chart = alt.Chart(df_lang_perc).mark_bar().encode(
    x=alt.X('Lang:N', sort='-y', title='Language'),
    y=alt.Y('perc_pos:Q', title='Percentage of Positive Reviews', scale=alt.Scale(domain=[0.7,1]), axis=alt.Axis(format='%')),
)

chart.display()

enter image description here

In the DataFrame, each language is categorized into a market. When I try to add color by language, Altair has a bug cropping the bars to the correct length.

chart = alt.Chart(df_lang_perc).mark_bar().encode(
    x=alt.X('Lang:N', sort='-y', title='Language'),
    y=alt.Y('perc_pos:Q', title='Percentage of Positive Reviews', scale=alt.Scale(domain=[0.7,1]), axis=alt.Axis(format='%')),
    color=alt.Color('market')
)

chart.display()

enter image description here

Is this a know issue and is there a workaround?

Minimal reproducible example:

df_lang_perc = pd.DataFrame({
    'Lang': ['brazilian', 'czech', 'english', 'latam', 'thai'],
    'perc_pos': [0.936053, 0.906603, 0.881611, 0.918832, 0.904748],
    'market': ['Latin_America', 'Europe', 'Emglish', 'Latin_America', 'Asia']
})
like image 687
Joscha Avatar asked Dec 17 '25 13:12

Joscha


1 Answers

I am not sure why this happens when you group by color, but it is related to clipping chart elements outside the axes, which you can force by using mark_bar(clip=True) as a workaround for your chart.

Edit: I actually think the error is in that the blue bars are being cut automatically (not sure if this is an Altair issue, or the frontend such as JupyterLab, etc). I believe bars are always extended to zero in VegaLite unless explicitly clipped to discourage zooming in on small difference unless it is done carefully and intentionally. This is also how that charts behave in the VegaLite online editor, where both the colored and not colored bars require the explicit clip=True to avoid extending beneath the x-axis.

like image 105
joelostblom Avatar answered Dec 19 '25 03:12

joelostblom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!