Search code examples
data-visualizationlinechartvega-litevega

How would I add a tooltip to a multi series line chart


I'm new to WebStorm and vega/vegalite and I am working on creating a visual with different types of gasoline and their prices from 1996-2020.

I've been able to create a graph with all of the information, but it's pretty hard to discern anything.

I've been going over the Vega-Lite documentation and I see that that I can use tooltips to zoom into the graphic. I tried implementing it, but I don't think I quite understand the scope of some of the properties.

Could someone show me how they might approach this task? Or perhaps even recommend videos or websites that might help me better understand how to do?

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Area charts of stock prices, with an interactive overview and filtered detail views.",
  "width": 720,
  "height": 480,
  "padding": 5,
  "data": {
    "name": "gas_prices",
    "url": "data/testInfo.csv",
    "format": {"type": "csv", "parse": {"A1": "number", "date": "date"}}
  },


  "repeat": {
    "layer": ["A1","A2","A3","R1","R2","R3","M1","M2","M3","P1","P2","P3","D1"]
  },


  "spec": {
    "mark": "line",
    "encoding": {
      "x": {
        "timeUnit": "yearmonth",
        "title": "Date",
        "field": "date"
      },
      "y": {
        "field": {"repeat":"layer"},
        "title": "Gas Prices",
        "type": "quantitative"
      },
      "color": {
        "datum": {"repeat": "layer"},
        "type": "nominal"
      }
    }


 }
}

Solution

  • You can refer the documentation for tooltip, which says about the options available to enable tooltips on your chart.

    Below is a sample config having default tooltip or refer editor:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "repeat": ["Horsepower", "Miles_per_Gallon", "Acceleration", "Displacement"],
      "columns": 2,
      "spec": {
        "data": {"url": "data/cars.json"},
        "mark": {"type": "bar", "tooltip": true},
        "encoding": {
          "x": {"field": {"repeat": "repeat"}, "bin": true},
          "y": {"aggregate": "count"},
          "color": {"field": "Origin"}
        }
      }
    }
    

    To have tooltips with some customizations, you can refer below code or editor:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "repeat": ["Horsepower", "Miles_per_Gallon", "Acceleration", "Displacement"],
      "columns": 2,
      "spec": {
        "data": {"url": "data/cars.json"},
        "mark": "bar",
        "encoding": {
          "tooltip": [
            {"aggregate": "count", "title": "YAxis"},
            {"field": {"repeat": "repeat"}, "title": "myXAxis"}
          ],
          "x": {"field": {"repeat": "repeat"}, "bin": true},
          "y": {"aggregate": "count"},
          "color": {"field": "Origin"}
        }
      }
    }