Search code examples
vega-lite

Arcs ordered by size in vega-lite pie chart


I'm trying to create a pie chart where the arcs are ordered by size (clockwise), but can't figure out how.

It seems that the "sort" argument in "theta" points to the default order of "color", for example:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A pie chart",
  "data": {
    "values": [
      {"category": "Category 1", "value": 4},
      {"category": "Category 2", "value": 8},
      {"category": "Category 4", "value": 25},
      {"category": "Category 0", "value": 12}
    ]
  },
  "encoding": {
    "color": {"field": "category", "type": "nominal"},
    "theta": {"field": "value", "type": "quantitative", "sort": "descending"}
  },
  "layer": [
    {"mark": {"type": "arc", "outerRadius": 85}}
  ],
  "view": {"stroke": null}
}

this is the result: arcs are ordered by reverse category name

I can sort the legend ("color") by "value", but no matter what I specify for "sort" of "theta", the arcs won't be sorted by "value" size.

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A pie chart",
  "data": {
    "values": [
      {"category": "Category 1", "value": 4},
      {"category": "Category 2", "value": 8},
      {"category": "Category 4", "value": 25},
      {"category": "Category 0", "value": 12}
    ]
  },
  "encoding": {
  "color": {"field": "category", "type": "nominal", "sort": {"field" :"value", "order": "ascending"}},
  "theta": {"field": "value", "type": "quantitative", "sort": "descending"}
  },
  "layer": [
    {"mark": {"type": "arc", "outerRadius": 85}}
  ],
  "view": {"stroke": null}
}

this is the result: legend is ordered, arcs still have the same order


Solution

  • It sounds like you want the order encoding. For example (open in editor):

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
      "description": "A pie chart",
      "data": {
        "values": [
          {"category": "Category 1", "value": 4},
          {"category": "Category 2", "value": 8},
          {"category": "Category 4", "value": 25},
          {"category": "Category 0", "value": 12}
        ]
      },
      "encoding": {
        "color": {"field": "category", "type": "nominal"},
        "theta": {"field": "value", "type": "quantitative", "stack": true},
        "order": {"field": "value", "type": "quantitative", "sort": "descending"}
      },
      "layer": [
        {"mark": {"type": "arc", "outerRadius": 85}}
      ],
      "view": {"stroke": null}
    }
    

    enter image description here