Tarantula
Tarantula

Reputation: 19843

Layered or Facet bar plot with label values in Altair

I'm trying to create a simple bar plot (with multiple columns for a specific field):

bars = alt.Chart(df_probing).mark_bar(stroke='transparent').encode(
    alt.X('model_name:N', scale=alt.Scale(rangeStep=12), axis=alt.Axis(title='')),
    alt.Y('acc:Q', axis=alt.Axis(title='Accuracy', grid=False)),
    color=alt.Color('model_name:N'),
    column='task_name:N'
).configure_view(
    stroke='transparent'
).configure_axis(
    domainWidth=0.8
) 

Now, this plot works well, but when I try to add the value labels on top of the bars like this:

text = bars.mark_text(
    align='center',
).encode(
    text='acc:Q'
)

bars + text

It throws the following error:

ValueError: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead.

How can bar labels be added to each bar in the bar plot on facet/layered plots ?

Upvotes: 3

Views: 5781

Answers (1)

jakevdp
jakevdp

Reputation: 86310

The configure_* methods only work for the top-level chart; the error is attempting to tell you this, but it's not as clear as it could be.

The solution is to move the configuration to the top-level object; that is, do something like this:

bars = alt.Chart(df_probing).mark_bar(stroke='transparent').encode(
    alt.X('model_name:N', title='', scale=alt.Scale(rangeStep=12)),
    alt.Y('acc:Q', title='Accuracy', axis=alt.Axis(grid=False)),
    color='model_name:N',
    column='task_name:N'
) 

text = bars.mark_text(
    align='center',
).encode(
    text='acc:Q'
)

alt.layer(bars, text).configure_view(
    stroke='transparent'
).configure_axis(
    domainWidth=0.8
)

Upvotes: 8

Related Questions