'Grouped bar chart in newer versions of altair (>= 4.2.0)

I am trying to create a grouped bar chart in altair like in the answer to this question here.

The particular interesting part is the "beautification:

chart = Chart(df).mark_bar().encode(
   column=Column('Genre', 
                 axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),
                 scale=Scale(padding=4.0)),
   x=X('Gender', axis=False),
   y=Y('Rating', axis=Axis(grid=False)),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display()

The issue is, however, that none of the stuff in the columns (alt.Column) works in the current version of Altair (I am using 4.2).

In particular, I am getting:

SchemaValidationError: Invalid specification altair.vegalite.v4.schema.channels.Column, validating 'additionalProperties' Additional properties are not allowed ('axis' was unexpected)

Can something similar still be done?



Solution 1:[1]

In Altair 4.2.0 you achieve a similar results like this (not sure if you can connect the facets with the x-axis line):

import altair as alt
import pandas as pd

# create dataframe
df = pd.DataFrame([['Action', 5, 'F'], 
                   ['Crime', 10, 'F'], 
                   ['Action', 3, 'M'], 
                   ['Crime', 9, 'M']], 
                  columns=['Genre', 'Rating', 'Gender'])

chart = alt.Chart(df).mark_bar().encode(
   column=alt.Column(
       'Genre', 
       header=alt.Header(orient='bottom')
    ),
   x=alt.X('Gender', axis=alt.Axis(ticks=False, labels=False, title='')),
   y=alt.Y('Rating', axis=alt.Axis(grid=False)),
   color='Gender'
).configure_view(
    stroke=None,
)

chart

enter image description here

In the current development version of Altair (will probably be released as 5.0), you can use the new offset channels to achieve the same result without faceting:

chart = alt.Chart(df).mark_bar().encode(
   x=alt.X('Genre', axis=alt.Axis(labelAngle=0)),
   xOffset='Gender',
   y=alt.Y('Rating', axis=alt.Axis(grid=False)),
   color='Gender'
).configure_view(
    stroke=None,
)

chart

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joelostblom