vega-lite

How to show conditional tooltip based on field?


I have a timeline chart with multiple transaction types (CASH, INV, CM etc.). Each transaction type will have different metadata that is relevant, and I'd like to surface that in the tooltips, and thus make them conditional on trx_type.

I know condition works within a simple tooltip:

"tooltip": {
   "condition": {
     "test": "(datum['trx_type'] !== 'CASH')",
     "field": "trx_type",
     "type": "nominal"
   },
   "value": "N/A"
 },

but can't seem to figure out how to use it within a more complex (multiple fields) setup:

"tooltip": [
   {
      "field": "trx_unixtime",
      "title": "Event Date",
      "type": "nominal",
      "timeUnit": "yearmonthdate"
   },
   {
      "field": "trx_type",
      "title": "Transaction Type"
   },
   {
      "field": "trx_count",
      "title": "# Transactions",
      "type": "quantitative",
      "format": ",.0f"
   }
]

Any suggestions on how to approach this?

timeline chart


Solution

  • You could use a transform calculate to handle this:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {"url": "data/barley.json"},
      "mark": "bar",
      "transform": [{"calculate": "datum.site ==='Crookston' ? datum.variety + ' (' + datum.site + ')': 'N/A'", "as": "tooltip_descr"}],
      "encoding": {
        "x": {"aggregate": "sum", "field": "yield"},
        "y": {"field": "variety"},
        "color": {"field": "site"},
        "tooltip": [
          {"field": "tooltip_descr", "type": "nominal", "title": "Field A"},
          {"field": "yield", "aggregate": "sum","type": "quantitative", "title": "Field B"}
        ]
      }
    }