C. Braun
C. Braun

Reputation: 5201

How do I make a grouped bar chart with a consistent grid across columns?

I am trying to make a grouped bar chart in Altair where the columns are not so obvious (probably by removing the space between them).

The solution proposed in the issue here relies on several depreciated methods. Additionally, the desired visual grouping described there (which is what I'm looking for) was closed as a vega-lite issue. This has since been resolved.

Is there an updated way to create a cleanly grouped bar chart?

Here's what I have so far:

import pandas as pd
import numpy as np
import altair as alt

vals = np.concatenate(((np.arange(10) ** 2) / 9, np.arange(10)))
df = pd.DataFrame({
    'cat': np.repeat(['a', 'b'], 10),
    'x': np.tile(np.arange(10), 2),
    'y': vals
})

alt.Chart(df).mark_bar(width=20).encode(
    x='cat',
    y='y',
    color='cat',
    column='x'
).configure_view(strokeWidth=0)

enter image description here

Is it possible to keep the horizontal grid lines while also maintaining the space between each group?

Upvotes: 4

Views: 749

Answers (1)

jakevdp
jakevdp

Reputation: 86433

You can combine facet spacing with adjusting the scale domain to do something like this:

import pandas as pd
import numpy as np
import altair as alt

vals = np.concatenate(((np.arange(10) ** 2) / 9, np.arange(10)))
df = pd.DataFrame({
    'cat': np.repeat(['a', 'b'], 10),
    'x': np.tile(np.arange(10), 2),
    'y': vals
})

alt.Chart(df).mark_bar(width=20).encode(
    x=alt.X('cat', scale=alt.Scale(domain=['', 'a', 'b'])),
    y='y',
    color='cat',
).facet(
    'x', spacing=0
).configure_view(
    strokeWidth=0
)

enter image description here

Upvotes: 6

Related Questions