How to create a grouped bar chart in Altair?
Asked Answered
F

2

14

How does one create a grouped bar chart in Altair? I'm trying the following but it is just producing two graphs side by side.

Chart(data).mark_bar().encode(
   column='Gender',
   x='Genre',
   y='Rating',
   color='Gender'
)

This is the image produce

Forsterite answered 5/5, 2017 at 5:47 Comment(0)
Y
14

Example of group bar chart

I show a simplified example of Grouped Bar Chart from Altair's documentation. You can also see the full documentation here.

Basically, you have to specify x-axis Gender (F or M in each subplot), y-axis as Rating and Genre as Column.

from altair import *
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 = Chart(df).mark_bar().encode(
   column=Column('Genre'),
   x=X('Gender'),
   y=Y('Rating'),
   color=Color('Gender', scale=Scale(range=['#EA98D2', '#659CCA']))
).configure_facet_cell(
    strokeWidth=0.0,
)

chart.display() # will show the plot

The bar chart will look like following

image

Adding Axis parameters

You only have to follow Axis parameters in documentation to make the plot looks prettier:

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()

Imgur

Yuri answered 5/5, 2017 at 9:13 Comment(9)
Could you explain the '.transform_data' section? It seems really involved just to get a grouped bar chart. I'm just starting out with data visualization so I don't know how this compares to other libraries.Forsterite
@KrisCampos, so Altair use grammar for plotting from vega and vega-lite. The syxtax will be heavily rely on these two. Transform basically specified fields that you can put to filter out or mapping data. See more on vega.github.io/vega-lite/docs/transform.html. For me, I feel like we don't mandatory need it since we can do filtering and cleaning up part using pandas directly.Yuri
Note that I just remove transformation part cause it doesn't affect the plot actually, haha.Yuri
The Altair documentation link for grouped bar charts is now updated to this page.Engler
Thanks @WR! I can update my solution and link it to the documentation page.Yuri
configure_facet_cell has been removed. To remove the facet outlines now just replace it with configure_view.Banded
I think these configuration are outdated because I get an error alt.Axis inside the column specification, do we have an updated version of the parameters to change to make the plot look like the second plot? (instead of the library example that looks like the first one)Agio
Yes please, can you make a suggestion to this answer? @AgioYuri
great answer! the colors are a bit stereotype though ;)Mitosis
I
4

If you try the accepted answers on newer version of Altair (since 4.2.0). You will notice that it doesn't work. Some of the API has changed, so to get the same results in Altair 4.2.0 you can use the approach posted in my answer to Grouped bar chart in newer versions of altair (>= 4.2.0). For the development version of Altair (which will probably be released as 5.0), this has become easier to achieve since you can use the xOffset encoding like this without the need to facet your charts:

import altair as alt
import pandas as pd

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(
   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

Ignatius answered 2/5, 2022 at 22:19 Comment(2)
This does not work in 5.0.1 despite having xOffset support. It just shows 2 stacked bars.Shipper
@Shipper It works for me, if you recently upgraded to altair 5, make sure you have closed any notebook using altair 4, and then restart your IDE. Having figures with altair 4 plots showing can prevent the upgrade. If that doesn't work, please submit a bug report on github with more detailsIgnatius

© 2022 - 2024 — McMap. All rights reserved.