2
votes

I have a data set that has multiple "values" in each row, e.g.:

"data": {
    "values": [
      {"date": "2020-01-01", "red":1, "green": 2},
      {"date": "2020-01-02", "red":3, "green": 4},
      {"date": "2020-01-03", "red":5, "green": 3},

    ]}

Based on my understanding of bar charts, each bar needs its own "row". Is there an inbuilt way to transpose the above data in Vega Lite and create a bar chart (with red and green stacked, so that it would total 3 on 1/1, 7 on 1/2, 8 on 1/3 and so forth)?

Thanks a lot for any help, J

1

1 Answers

0
votes

Yes, this is exactly what the Fold Transform is designed for. For example (vega editor):

{
  "data": {
    "values": [
      {"date": "2020-01-01T00:00:00", "red": 1, "green": 2},
      {"date": "2020-01-02T00:00:00", "red": 3, "green": 4},
      {"date": "2020-01-03T00:00:00", "red": 5, "green": 3}
    ]
  },
  "transform": [{"fold": ["red", "green"], "as": ["color", "value"]}],
  "mark": "bar",
  "encoding": {
    "x": {"field": "date", "type": "ordinal", "timeUnit": "yearmonthdate"},
    "y": {"type": "quantitative", "field": "value"},
    "color": {"field": "color", "type": "nominal", "scale": null}
  }
}

enter image description here

Some notes:

  • I changed your dates to ISO format because this works best in Vega-Lite. Javascript date parsing behavior varies from browser to browser, but all browsers parse ISO consistently.
  • setting "scale": null causes the colors to be drawn from the data, rather than generating a mapping from data values to a color scale.