【问题标题】:Add data labels to vega-lite bar chart将数据标签添加到 vega-lite 条形图
【发布时间】:2017-07-19 20:11:36
【问题描述】:

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

生成图表的代码是:

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 功能,如果我使用分层,这可能是一个选项,但我找不到如何旋转文本。当然,如果有更好的方法(或者根本不可能),一定要告诉! 谢谢!

【问题讨论】:

    标签: python vega-lite altair


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        猜你喜欢
        • 2020-09-18
        • 2021-08-22
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多