Protaeus
Protaeus

Reputation: 159

Altair to generate horizontal bar chart with horizontally concatenated table

If possible, I would like to use altair to create a horizontal bar chart with a column or columns from a table that is horizontally concatenated and aligns with the bar. I'm pasting an example of quick excel chart to get a rough idea of what I'm wanting.

example

The following example from your website (code and then image), which I subsetted for the sake of space, is similar to what I would like. However, rather than have a text overlay with the value corresponding to the bar length, I want to create a horizontal bar chart with value "x" and a horizontally concatenated table with a separate value, "p", that corresponds to that sample.

import altair as alt
from vega_datasets import data

source = data.wheat()
sourceTrunc = source.head(15)

bars = alt.Chart(sourceTrunc).mark_bar().encode(
    x='wheat:Q',
    y="year:O"
)

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'
)

(bars + text).properties(height=400)

foundation

Upvotes: 3

Views: 2449

Answers (1)

jakevdp
jakevdp

Reputation: 86433

You can use horizontal concatenation in place of layering to achieve this. For example:

import altair as alt
from vega_datasets import data

source = data.wheat()
sourceTrunc = source.head(15)

bars = alt.Chart(sourceTrunc).mark_bar().encode(
    x='wheat:Q',
    y="year:O"
)

text = alt.Chart(sourceTrunc).mark_text().encode(
    y=alt.Y('year:O', axis=None),
    text='wheat:Q'
).properties(width=30)

bars | text

enter image description here

Upvotes: 2

Related Questions