Search code examples
vega-lite

Dynamic scale domain in vega-lite


I would like to define my x-axis:

  • minimum value should be now()

  • maximum value should be automatically determined (just as if the domain of the scale would have not been defined)

       "encoding": {
     "y": {
       "field": "Reference",
       "type": "nominal",
       },
     "x":{
       "field": "Date",
       "type": "temporal",
       "scale": {"domain": [now(), 1618000000000]}}
    

I also tried to use an expression to set-up now(), to no success:

"scale": {"domain": ["expr":"now()", 1618000000000]

Solution

  • You were quite close with the second attempt; you just need to put braces around the expression statement:

    "scale": {"domain": [{"expr": "now()"}, "2021-05-01T00:00:00"]}
    

    Here's a full example (open in editor):

    {
      "data": {
        "values": [
          {"date": "2021-03-01T00:00:00", "value": 1},
          {"date": "2021-04-01T00:00:00", "value": 3},
          {"date": "2021-05-01T00:00:00", "value": 2}
        ]
      },
      "mark": "line",
      "encoding": {
        "x": {
          "field": "date",
          "type": "temporal",
          "scale": {"domain": [{"expr": "now()"}, "2021-05-01T00:00:00"]}
        },
        "y": {"field": "value", "type": "quantitative"}
      }
    }
    

    enter image description here

    If instead of setting the domain limits, you just want to ensure that now() appears as part of the domain, you can use a domain unionWith statement:

    "scale": {"domain": {"unionWith": [{"expr": "now()"}]}}
    

    This will create an automatically calculated domain that contains the current date.