Altair - Bar Chart Domain Cropping Error when adding Color

Viewed 185

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']
})
2 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.

Adding clamp=True to the scale argument of Y (or to a separate configure_scale) also fixes this.

The docs state that True is default however and also setting clamp=False to the 'non-colored' bar chart, doesn't extent the bars either.
alt.Scale Documentation

Related