0
votes

I have data formatted with multiple fields per x:

x1 f1 f2 f3
x2 f4 f5 f6
...

This is so I can use tooltips with custom formatting (showing all the values for a single x) and so that I can customize the mark for each field. link to sample.

I would like to add a legend to show the meaning of the colors, but I can't make one auto generate for the multiple fields. I was thinking of adding a second dataset with discrete values for the fields and colors (something like this), but apparently you can't add multiple sets to vega-lite, and I don't know enough to move to pure vega. Is this possible?

1

1 Answers

0
votes

The best way to generate a legend from multiple columns is to use a Fold Transform to fold them into a single column, then let the encodings handle the legend for you. Modifying the example you linked to, it might look something like this: (vega editor link):

{
  "data": {"url": "data/seattle-weather.csv", "format": {"type": "csv"}},
  "encoding": {
    "x": {"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
    "tooltip": [
      {"timeUnit": "yearmonthdate", "field": "date", "type": "temporal"},
      {"field": "temp_max", "type": "quantitative"},
      {"field": "temp_min", "type": "quantitative"}
    ]
  },
  "layer": [
    {
      "transform": [
        {"fold": ["temp_min", "temp_max"], "as": ["measure", "temp"]}
      ],
      "mark": {"type": "line"},
      "encoding": {
        "y": {"field": "temp", "type": "quantitative"},
        "color": {"field": "measure", "type": "nominal"}
      }
    },
    {
      "mark": "rule",
      "selection": {
        "hover": {"type": "single", "on": "mouseover", "empty": "none"}
      },
      "encoding": {
        "color": {
          "condition": {"selection": {"not": "hover"}, "value": "transparent"}
        }
      }
    }
  ],
  "config": {"axisY": {"minExtent": 30}}
}

enter image description here

Notice that we've replaced the two temp_min/temp_max layers with a single layer that transforms the data and encodes color by column name, automatically generating a legend.