4

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

Firas
  • 516
  • 5
  • 10

2 Answers2

4

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

jakevdp
  • 77,104
  • 11
  • 125
  • 160
  • Great, thanks for the info! Is there a way to make the bar groups closer to each other? Basically shrink the distance between the different 'sites' – zylatis Dec 02 '19 at 04:00
  • 1
    Try e.g. ``chart.configure_facet(spacing=5)`` to control the space between sites in pixels. – jakevdp Dec 02 '19 at 04:03
2

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!

Firas
  • 516
  • 5
  • 10