Search code examples
vega-lite

Is there a way to pass the aggregated value to the tooltip encoding on a simple histogram in Vega Lite


I would like to add the value of the count to the tooltip in the simple way to a simple histogram plot in Vega Lite?

Something like this:

{
  "data": {
    "url": "data/movies.json"
  },
  "mark": "bar",
  "encoding": {
    "tooltip": [
      {
        "field":  "Count of Records",
        "type": "quantitative"
      }
    ],
    "x": {
      "bin": true,
      "field": "IMDB_Rating",
      "type": "quantitative"
    },
    "y": {
      "aggregate": "count",
      "type": "quantitative"
    }
  }
}

There does not seem to be a way to reference the aggregated y encoding in the tooltip encoding.


Solution

  • Tooltips are encodings just like any other; you can pass the same arguments to the tooltip that you do to the y encoding:

    {
      "data": {
        "url": "data/movies.json"
      },
      "mark": "bar",
      "encoding": {
        "tooltip": [
          {
            "aggregate": "count",
            "type": "quantitative"
          }
        ],
        "x": {
          "bin": true,
          "field": "IMDB_Rating",
          "type": "quantitative"
        },
        "y": {
          "aggregate": "count",
          "type": "quantitative"
        }
      }
    }
    

    See it in action here.