将数据标签添加到vega-lite条形图

时间:2017-07-19 20:11:37

标签: python vega-lite altair

我有一个相当简单的条形图,使用Python altair库创建,基于Pandas DataFrame。

Bar chart

生成图表的代码是:

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

这转换为以下vega-lite语法:

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

我唯一要添加的是每个条形图中(或上方)的实际值,最好是逆时针旋转90°。

到目前为止,我只能找到mark_text功能,如果我使用分层,这可能是一个选项,但我找不到如何旋转文本。当然,如果有更好的方式(或者根本不可能),请告诉我们! 谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用text config按指定角度旋转。从本质上讲,您可能希望执行以下操作:mark_text(angle=-90, dx=10)

答案 1 :(得分:0)

This example from the docs gallery 展示了如何向条形添加文本:

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)
相关问题