mlmisha
mlmisha

Reputation: 1

Labeling one bar in altair

I'd like to label one exact bar in bar chart made up by altair, but I can't find the information about that option - only labeling the whole plot, which I'm not interested at. May be there is something like altair.condition for coloring, for example? So I can label a bar according to the condition. Thank you!

Upvotes: 0

Views: 564

Answers (1)

Robin Dhillon
Robin Dhillon

Reputation: 43

Labeling one bar is doable, there are just a few extra steps. I'll be using the built-in airports dataset to demonstrate.

from vega_datasets import data
import altair as alt

airports = data.airports().query("country == 'USA'").dropna()

airports['label'] = False  # create new column
airports.loc[airports['state'] == 'NY', 'label'] = True  # choose state to label in the new column

airports_bar = alt.Chart(airports).mark_bar().encode(
    y=alt.Y('state:N', sort = 'x'),
    x=alt.X('count()', axis=alt.Axis(grid=False)),
    color=alt.Color('label', legend=None),
    tooltip=['count()']
)

As explained in the comments in the code above, we simply create a new column which will contain the bar that we want to label. I chose to label NY; once we create the new column, we simply set its value of NY to be True. This will then be used in the color argument to color NY separately from all the other states. To label NY with the count value, we use mark_text in which we filter/query for NY specifically, not the whole dataframe. This allows us to only label NY and not the other states. The code and plot is shown below:

airports_bar + alt.Chart(airports.query("state == 'NY'")).mark_text(dx=10).encode(
    y=alt.Y('state:N'),
    x=alt.X('count()', axis=alt.Axis(grid=False)),
    text='count()')

enter image description here

Note that, although not shown in this demonstration, we should be sorting the bars by the counts. Hopefully this answered your question!

Upvotes: 1

Related Questions