1
votes

I have a rather simple bar chart, created with the Python altair library, based on a Pandas DataFrame.

Bar chart

The code to generate the chart is:

Chart(df).configure(background='white').mark_bar().encode(
    X('user_id', bin=Bin(maxbins=10), title='Subscriber count'),
    Y('count(*)', title='Number of publications')
)

Which translates to the following vega-lite syntax:

{
    "encoding":
    {
        "x":
        {
            "bin":
            {
                "maxbins": 10
            },            "field": "user_id",
            "title": "Subscriber count",
            "type": "quantitative"
        },
        "y":
        {
            "aggregate": "count",
            "field": "*",
            "title": "Number of publications"
        }
    },
    "mark": "bar"
}

The only thing I'd like to add, are the actual values in (or on) each bar, preferably rotated 90° counter-clockwise.

So far, I've only been able to find the mark_text feature, which might be an option if I used layering, but I can't find how to rotate the text. Of course, if there's a better way (or if it's not possible at all), do tell! Thanks!

2

2 Answers

0
votes

You can use text config to rotate by a specified angle. Essentially, you may want to do something like: mark_text(angle=-90, dx=10).

0
votes

This example from the docs gallery shows how to add text to bars:

import altair as alt
from vega_datasets import data

source = data.wheat()

bars = alt.Chart(source).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=900)