Iulia Mihet
Iulia Mihet

Reputation: 700

Create a discontinued line chart using Vega lib

I am looking to create this kind of chart in Vega:

A basic Excel discontinued line chart

I carefully read the documentation about marks here: https://vega.github.io/vega/docs/marks/line/

I read about the Type-Specific Mark Properties and about the defined property and it seemed like what I need. But I have no idea how to use this property.

I have my marks defined like so:

'marks': [
      {
        'name': 'expected_sales',
        'description': 'The sales line',
        'type': 'line',
        'defined': 'false', // this I added based on the documentation
        'from': {
          'data': 'SalesData'
        },
        'zindex': 100,
        'encode': { ... }
      }
 ]

But this apparently doesn't work. the line is still continued. I have to mention that the data points that I get don't have null values, but 0.0.

Upvotes: 3

Views: 286

Answers (1)

codex
codex

Reputation: 702

Considering that sales might be $0 at some point, it is better to deferentiate between 0 values and null values.

That said, because null values are defined as 0.0 in the dataset, defined property has to be true for all other points except when value is 0.0

In the below example, "defined": {"signal": "datum.v !== 0.0"} is used to conditionally assign "defined" property to false if value "datum.v" is 0.0

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 200,
  "padding": 5,

  "data": [
    {
      "name": "table",
      "values": [
        {"u": 1, "v": 28}, {"u": 2, "v": 12.0},
        {"u": 3, "v": 0.0}, {"u": 4, "v": 10},
        {"u": 5, "v": 36}, {"u": 6, "v": 44}
      ]
    }
  ],

  "scales": [
    {
      "name": "xscale",
      "type": "linear",
      "range": "width",
      "zero": false,
      "domain": {"data": "table", "field": "u"}
    },
    {
      "name": "yscale",
      "type": "linear",
      "range": "height",
      "nice": true,
      "zero": false,
      "domain": {"data": "table", "field": "v"}
    }
  ],
  "axes": [
    {"scale": "xscale", "orient": "bottom", "grid": true},
    {"scale": "yscale", "orient": "left"}

  ],

  "marks": [
    {
      "type": "line",
      "from": {"data": "table"},
      "encode": {
        "enter": {
          "stroke": {"value": "#652c90"}
        },
        "update": {
          "x": {"scale": "xscale", "field": "u"},
          "y": {"scale": "yscale", "field": "v"},
          "defined": {"signal": "datum.v !== 0.0"},
          "interpolate": {"value": "linear"},
          "strokeWidth": {"value": 4},
          "strokeDash": {"value": [1,0]},
          "strokeCap": {"value": "square"},
          "opacity": {"value": 1}
        },
        "hover": {
          "opacity": {"value": 0.5}
        }
      }
    }
  ]
}

Upvotes: 1

Related Questions