Search code examples
vega-lite

How to create relative mark positions in Vega LIte


I have a pie chart with width & height set to "container". I would like to label each slice of the pie. Therefore I included a layer and it creates the correct text. However, I don't know how to implement a relative radius size. How would you go about it?

With an absolute radius (e.g. 30) it works, but I need a relative position.

`"layer": [{"mark": {"type": "arc"}},
{"mark": {"type": "text", "radius":30},
"encoding": {"text": {"field": "*", "type": "nominal"}}
}]`

Solution

  • You can create relative radii using an Expression Reference for the radius value.

    For example, here is a chart where the radius of the pie chart is set to 40% of the chart size, and the text is set at 45% of the chart size (here I chose to measure the chart size as the minimum of the width and height, which seems reasonable for a circular chart):

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
      "description": "A simple pie chart with labels.",
      "data": {
        "values": [
          {"category": "a", "value": 4},
          {"category": "b", "value": 6},
          {"category": "c", "value": 10},
          {"category": "d", "value": 3},
          {"category": "e", "value": 7},
          {"category": "f", "value": 8}
        ]
      },
      "encoding": {
        "theta": {"field": "value", "type": "quantitative", "stack": true}
      },
      "layer": [
        {
          "mark": {"type": "arc", "radius": {"expr": "0.4 * min(width, height)"}},
          "encoding": {"color": {"field": "category", "type": "nominal", "legend": null}}
        },
        {
          "mark": {"type": "text", "radius": {"expr": "0.45 * min(width, height)"}},
          "encoding": {"text": {"field": "category", "type": "nominal"}}
        }
      ],
      "view": {"stroke": null}
    }
    

    enter image description here

    (open in editor)