altair grouped bar chart side-by-side instead of single chart

Viewed 345

I tried creating the chart however it ends up showing two charts side-by-side. How do I get a single chart instead like the one shown in altair grouped bar chart example.

df = pd.DataFrame({
    'strike': [200,225,250,275,300,325,350,200,225,250,275,300,325,350],
    'opttype': ['ce','ce','ce','ce','ce','ce','ce','pe','pe','pe','pe','pe','pe','pe' ],
    'oi': [100,150,500,800,450,200,77,50,500,210,300,150,60,17]
    
})
c = alt.Chart(df).mark_bar().encode(
    x='strike:N',
    y='oi:Q',
    color='opttype:N',
    column='opttype:N'
)

Output output

I tried adding axis as specified in this link, however I could not get the combined graph. May be I am missing something here.

Also I wonder how the official documentation example works correcly without the "axis" as well.

2 Answers

The current best way to do this is to switch your x and column encodings, then make the width of each panel narrower:

c = alt.Chart(df).mark_bar().encode(
    x='opttype:N',
    y='oi:Q',
    color='opttype:N',
    column='strike:N'
).properties(width=50)

enter image description here

Then, if you wish, you can adjust axis & heading labels as in the linked examples. For example, you can move the header labels to the bottom like this:

c = alt.Chart(df).mark_bar().encode(
    x=alt.X('opttype:N', axis=None),
    y='oi:Q',
    color='opttype:N',
    column=alt.Column('strike:N', header=alt.Header(orient='bottom'))
).properties(width=50)

enter image description here

This is admittedly an imperfect solution. Vega-Lite is in the process of adding an offset encoding that will make this possible without having to use multiple column facets, but that is not available yet.

The x-axis and color variable should be the same:

df = pd.DataFrame({
    'strike': [200,225,250,275,300,325,350,200,225,250,275,300,325,350],
    'opttype': ['ce','ce','ce','ce','ce','ce','ce','pe','pe','pe','pe','pe','pe','pe' ],
    'oi': [100,150,500,800,450,200,77,50,500,210,300,150,60,17]
})

alt.Chart(df).mark_bar().encode(
    x='opttype:N',
    y='oi:Q',
    color='opttype:N',
    column='strike:N'
)

enter image description here

Related