Search code examples
jsonvisualizationvega-lite

How to add different mark types in the legend


I'd like to provide a name for a mark rule via some mark's property (which one), and then add it to the legend? Is it possible?

I need to provide a few such rules on a chart, so it would be useful to see them all on the legend.

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"X": 1, "Y": 2, "Series": "A"}, 
      {"X": 1, "Y": 3, "Series": "B"}, 
      {"X": 2, "Y": 3, "Series": "A"}, 
      {"X": 2, "Y": 4, "Series": "B"}, 
      {"X": 3, "Y": 4, "Series": "A"}, 
      {"X": 3, "Y": 5, "Series": "B"},
      {"X": 4, "Y": 3, "Series": "A"}, 
      {"X": 4, "Y": 4, "Series": "B"},
      {"X": 5, "Y": 2, "Series": "A"}, 
      {"X": 5, "Y": 3, "Series": "B"}
    ]
  },
  "encoding": {
    "x": {"field": "X", "type": "nominal"},
    "y": {"field": "Y", "aggregate": "sum", "type": "quantitative"},
    "color": {"field": "Series"}
  },
  "layer":[
    {
      "mark":"bar"
    },
    {
      "mark": {
        "type": "rule",
        "stroke": "red",
        "strokeWidth": 1,
        "strokeDash": [8,4]
      },
      "encoding":{
        "x": {},
        "y": {"datum": 6}
      }     
    }    
  ]
}

Vega Lite Editor

Chart


Solution

  • Here you go. You might be better off using Vega instead of VL once your viz gets more complicated.

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "encoding": {
        "x": {"field": "X", "type": "nominal"},
        "y": {"field": "Y", "aggregate": "sum", "type": "quantitative"}
      },
      "layer": [
        {
          "data": {
            "name": "a",
            "values": [
              {"X": 1, "Y": 2, "Series": "A"},
              {"X": 1, "Y": 3, "Series": "B"},
              {"X": 2, "Y": 3, "Series": "A"},
              {"X": 2, "Y": 4, "Series": "B"},
              {"X": 3, "Y": 4, "Series": "A"},
              {"X": 3, "Y": 5, "Series": "B"},
              {"X": 4, "Y": 3, "Series": "A"},
              {"X": 4, "Y": 4, "Series": "B"},
              {"X": 5, "Y": 2, "Series": "A"},
              {"X": 5, "Y": 3, "Series": "B"}
            ]
          },
          "mark": "bar",
          "encoding": {
            "fill": {"field": "Series", "legend": {"symbolType": "square"}}
          }
        },
        {
          "data": {"name": "b", "values": [{"Y": 6, "Series": "Goal", "C": "red"}]},
          "mark": {"type": "rule", "strokeWidth": 1, "strokeDash": [8, 4]},
          "encoding": {
            "x": {},
            "y": {"field": "Y"},
            "color": {
              "field": "Series",
              "legend": {"symbolType": "stroke"},
              "scale": {"range": {"field": "C"}}
            }
          }
        }
      ]
    }