Search code examples
vega-lite

Create array for x axis with known min, max and step


I am trying to create values for x axis for each y data point and I can't create a formula.

This is what I am trying to achieve:

Chart

Here is my code:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data":{ 
"values":[
  {
   "days": {
            "min" : 0,
            "max" : 10,
            "step" : 2,
            "count" : [0.2,0.6,0.4,0.3,0.1]
          }}
]},

"transform": [
  {"calculate": "datum.days.count", "as": "y"},
  {"flatten": ["y"]},
  {"calculate": "datum.max/datum.step", "as": "x"}
],
"mark": "line",
      "encoding": {
        "x": { "scale": {"type": "linear", "domain":[0,10], "exponent": 2},"field": "x", 
        "type": "quantitative"
        },
        
        "y": { 
          "field": "y",
          "type": "quantitative"
          
        }

 
}}

Where count is on y axis and I need generate x axis values for each y point using "min","max" and "step" data (something like "x":[1,2,3,4,5]).

I tried scale function but it didn't work.

I need the x axis to have labels 0,2,4,6,8,10 - because my data max is 10 and step is 2 (10/2).


Solution

  • I'm not sure I fully understand what you're trying to achieve but does the following help? enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {
        "values": [
          {
            "days": {
              "min": 0,
              "max": 10,
              "step": 2,
              "count": [0.2, 0.6, 0.4, 0.3, 0.1]
            }
          }
        ]
      },
      "transform": [
        {"calculate": "datum.days.count", "as": "y"},
        {"flatten": ["y"]},
        {
          "window": [{"op": "count", "field": "count", "as": "i"}],
          "frame": [null, 0]
        },
         {"calculate": "(datum.i-1)*2", "as": "x"}
      ],
      "mark": "line",
      "encoding": {
        "x": {
          "scale": {"type": "linear", "domain": [0, 10], "exponent": 2},
          "field": "x",
          "type": "quantitative"
        },
        "y": {"field": "y", "type": "quantitative"}
      }
    }