mouse
mouse

Reputation: 35

Grouped bar chart in altair

I've read the altair grouped bar chart example, but the bars are based on the same column of data. Is it possible to have separate bars based on different columns of data?

For example, my data looks like this:

house  price_2010    price_2020
1      42342.5       233442.34
2      145124        2342235.50

How can I make a grouped bar chart with the charts as price_2010 and price_2020?

Upvotes: 0

Views: 2143

Answers (1)

jakevdp
jakevdp

Reputation: 86533

You have what some people call wide-form data, and Altair works best with long-form data. See Altair's documentation for more discussion.

Short version: if you want to do a grouped bar chart with this kind of data, you'll first have to re-shape the dataframe. The melt() method can be helpful for this:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'index': range(5),
    'price_2010': [12, 14, 10, 9, 6],
    'price_2020': [14, 15, 12, 14, 10]
})

alt.Chart(df.melt('index')).mark_bar().encode(
    alt.X('variable:N', axis=alt.Axis(title='')),
    alt.Y('value:Q', axis=alt.Axis(title='price', grid=False)),
    color=alt.Color('variable:N'),
    column='index:O'
).configure_view(
    stroke='transparent'
)

enter image description here

Note also that when Altair 3.0 is released, it will include the fold transform, which will allow you to do the operation done by df.melt() as part of the chart specification, rather than as a pre-processing step.

Upvotes: 3

Related Questions