简体   繁体   中英

Altair: How to add labels to bar charts that have rows

When trying to add labels to an Altair bar chart which has rows, I get an SchemaValidationError. I'm talking about labels like here: https://altair-viz.github.io/gallery/bar_chart_with_labels.html

And I'm talking about bar charts with rows or "horizontal grouped bar charts" like this: https://altair-viz.github.io/gallery/grouped_bar_chart_horizontal.html

Here is the code that does NOT work:

from vega_datasets import data

source = data.barley()

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O',
    row='variety:N',
)
bars

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='sum(yield):Q'
)

bars + text

If I remove the row option in the bar chart it works as expected:

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O'
)
bars

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='sum(yield):Q'
)

bars + text

Adding the rows to the 'mark_text' method also does not help...

In the end I'd like to see labels to the right of my bars like indicated here: https://imgur.com/KFJtNkb

The error from your code snippet is

ValueError: Faceted charts cannot be layered.

In general, there is no guarantee that two faceted charts will have matching facets that are able to be layered, so Vega-Lite does not allow faceted charts to be layered.

The way to get around this is to facet a layered chart rather than layer a faceted chart. For example:

import altair as alt
from vega_datasets import data

source = data.barley()

bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield):Q',
    y='year:O',
)
bars

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='sum(yield):Q'
)

(bars + text).facet(row='variety:N')

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM