【问题标题】:How to vertically align Vega-Lite stacked bar chart data labels如何垂直对齐 Vega-Lite 堆叠条形图数据标签
【发布时间】:2022-02-05 23:33:55
【问题描述】:

如何对齐堆积条形图中的数据标签,使其在每个条形段内垂直居中?在以下示例中,您可以看到文本位于每个条形段的顶部。在条形段较细的地方,数据标签与下面的标签重叠。我意识到即使标签垂直居中,具有多个相邻的细线段也会导致重叠,但我的数据集不太可能出现这种情况。

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.json",
  "data": {
    "values": [
      {"Value": 0.321, "Date": "09/30/2021", "Measure": "Measure 4"},
      {"Value": 0.031, "Date": "09/30/2021", "Measure": "Measure 3"},
      {"Value": 0.123, "Date": "09/30/2021", "Measure": "Measure 2"},
      {"Value": 0.475, "Date": "09/30/2021", "Measure": "Measure 1"}
    ]
  },
  "width": 500,
  "height": 250,
  "resolve": {"scale": {"color": "independent"}},
  "layer": [
    {
      "mark": "bar",
      "encoding": {
        "y": {
          "field": "Value",
          "type": "quantitative",
          "axis": {"format": ".1%"}
        },
        "x": {"field": "Date", "type": "nominal", "axis": {"labelAngle": -45}},
        "color": {"field": "Measure", "type": "nominal"}
      }
    },
    {
      "mark": {"type": "text"},
      "encoding": {
        "y": {"field": "Value", "type": "quantitative", "stack": "zero"},
        "x": {"field": "Date", "type": "nominal"},
        "color": {
          "field": "Measure",
          "type": "nominal",
          "scale": {"range": ["white"]},
          "legend": null
        },
        "text": {
          "aggregate": "sum",
          "field": "Value",
          "type": "quantitative",
          "format": ".1%"
        }
      }
    }
  ]
}

【问题讨论】:

    标签: vertical-alignment vega-lite stacked-chart


    【解决方案1】:

    您可以使用stackcalculate 转换来做到这一点。文本层如下所示:

        {
          ...
          "transform": [
            {"stack": "Value", "groupby": ["Date"], "as": ["lower", "upper"]},
            {"calculate": "(datum.lower + datum.upper) / 2", "as": "midpoint"}
          ],
          "encoding": {
            "y": {"field": "midpoint", "type": "quantitative"},
            ...
          }
        }
    

    您可以在vega editor 中查看完整规范:

    【讨论】:

    • 太棒了!谢谢杰克!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2013-12-07
    • 2022-08-19
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多