Firas
Firas

Reputation: 526

Produce "dodged" or "side-by-side" bar/column charts in Altair?

Apologies if this has been asked before, but I'm looking for a way to create bar-charts that are "dodged" (language from ggplot2) using the Altair library in python.

I know Altair has this example:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    x='year:O',
    y='sum(yield):Q',
    color='year:N',
    column='site:N'
)

That produces this plot:

Altair Plot

However, this has a lot of redundant labels and information. Ideally I want a plot where the paired bars encode the year in colour (blue is 1931 and orange is 1932) and then the cities running along the x-axis (ordinal variable).

Hard to explain, but here's an example of how to get a plot like this from seaborn (using different data; source isthis SO question):

Seaborn Plot

Upvotes: 4

Views: 4149

Answers (2)

Firas
Firas

Reputation: 526

In case anyone ends up here through google etc, here's the code to bring the bars closer together:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    alt.X('year:O', axis=None),#axis=alt.Axis(title=None, labels=False, ticks=False)),
    alt.Y('sum(yield):Q', axis=alt.Axis(grid=True)),
    alt.Facet('site:N',title="Facet title Here",),
    color='year:N',
).properties(height=150, width=80).configure_view(
    stroke='transparent'
).configure_scale(bandPaddingInner=0,
                  bandPaddingOuter=0.1,
).configure_header(labelOrient='bottom',
                   labelPadding = 3).configure_facet(spacing=5
)

Result:

Grouped Bar chart

Thanks to Jake for pointing me in the right direction with his answer!

Upvotes: 3

jakevdp
jakevdp

Reputation: 86443

Yes, you've found the recommended way to create grouped bar charts in Altair. If you want to adjust the final look of the chart, you can do things like removing & rearranging labels and titles; here's how you might modify your example to make it closer to the seaborn chart:

import altair as alt
from vega_datasets import data

source = data.barley()

alt.Chart(source).mark_bar().encode(
    x=alt.X('year:O', axis=alt.Axis(title=None, labels=False, ticks=False)),
    y=alt.Y('sum(yield):Q', axis=alt.Axis(grid=False)),
    color='year:N',
    column=alt.Column('site:N', header=alt.Header(title=None, labelOrient='bottom'))
).configure_view(
    stroke='transparent'
)

enter image description here

Upvotes: 4

Related Questions