Interactive Index Chart

View this example in the online editor

Vega-Lite JSON Specification

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "url": "data/stocks.csv",
    "format": {"parse": {"date": "date"}}
  },
  "width": 650,
  "height": 300,
  "layer": [
    {
      "params": [{
        "name": "index",
        "value": [{"x": {"year": 2005, "month": 1, "date": 1}}],
        "select": {
          "type": "point",
          "encodings": ["x"],
          "on": "pointerover",
          "nearest": true
        }
      }],
      "mark": "point",
      "encoding": {
        "x": {"field": "date", "type": "temporal", "axis": null},
        "opacity": {"value": 0}
      }
    },
    {
      "transform": [
        {
          "lookup": "symbol",
          "from": {"param": "index", "key": "symbol"}
        },
        {
          "calculate": "datum.index && datum.index.price > 0 ? (datum.price - datum.index.price)/datum.index.price : 0",
          "as": "indexed_price"
        }
      ],
      "mark": "line",
      "encoding": {
        "x": {"field": "date", "type": "temporal", "axis": null},
        "y": {
          "field": "indexed_price", "type": "quantitative",
          "axis": {"format": "%"}
        },
        "color": {"field": "symbol", "type": "nominal"}
      }
    },
    {
      "transform": [{"filter": {"param": "index"}}],
      "encoding": {
        "x": {"field": "date", "type": "temporal", "axis": null},
        "color": {"value": "firebrick"}
      },
      "layer": [
        {"mark": {"type": "rule", "strokeWidth": 0.5}},
        {
          "mark": {"type": "text", "align": "center", "fontWeight": 100},
          "encoding": {
            "text": {"field": "date", "timeUnit": "yearmonth"},
            "y": {"value": 310}
          }
        }
      ]
    }
  ]
}