Search code examples
javascriptvega-lite

Vega-Lite Wilkinson Dot Plot, group by first digit


I see the code to create a Wilkinson Dot Plot in Vega-Lite:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "A Wilkinson Dot Plot",
  "height": 100,
  "data": {
    "values": [
      10,11,11,11,14,15,17,
      22,25,26,28,
      33,33,33,34,37
    ]
  },
  "transform": [{
    "window": [{"op": "rank", "as": "id"}],
    "groupby": ["data"]
  }],
  "mark": {
    "type": "circle",
    "opacity": 1
  },
  "encoding": {
    "x": {"field": "data", "type": "ordinal"},
    "y": {"field": "id", "type": "ordinal", "axis": null, "sort": "descending"}
  }
}

Creates a plot grouping the exact numbers, but I'd like the output to be by the first digit so really theres 7 vertical dots for 1, 4 vertical dots for 2, and 5 vertical dots for 3. I tried adding calculation: "str.map(x => x.charAt(0))" to the transform array so I could group by that, but was unsuccessful in my execution. Any ideas appreciated!


Solution

  • You were on the right track, except that calculate transforms cannot use arbitrary javascript code, but only the subset made available in Vega Expressions. So, for example, you could do something like this (vega editor):

    {
      "data": {
        "values": [10, 11, 11, 11, 14, 15, 17, 22, 25, 26, 28, 33, 33, 33, 34, 37]
      },
      "transform": [
        {"calculate": "floor(datum.data / 10)", "as": "data"},
        {
          "window": [{"op": "rank", "field": "data", "as": "id"}],
          "groupby": ["data"]
        }
      ],
      "mark": {"type": "circle", "opacity": 1},
      "encoding": {
        "x": {"field": "data", "type": "ordinal"},
        "y": {"field": "id", "type": "ordinal", "axis": null, "sort": "descending"}
      }
    }
    

    enter image description here