Displaying a horizontal rule at constant value in Vega-Lite, does not show up

Viewed 148

I am trying to display a horizontal rule at a constant value in Vega-Lite, without success. Here is the code (can be pasted in https://vega.github.io/editor/#/):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",

  "encoding": {
    "x": {"field": "ts", "type": "temporal"},
    "y": {"field": "a", "type": "quantitative"}
  },

  "layer": [
    {
      "data": {
        "values": [
          {"ts": "2021-11-26", "a": 0.16},
          {"ts": "2021-11-28", "a": 0.12}
        ]
      },
      "mark": { "type": "point" }
    },

    {
      "data": { "values": [] },
      "mark": {"type": "rule", "color": "red"},
      "encoding": {"y": {"datum": 0.15, "type": "quantitative"}}
    }
  ]
}

In this code, I use a second layer to overlay a rule for a constant value, but it just doesn't show up. Any ideas?

1 Answers

There are two issues here:

  1. Your top level encoding maps x to field ts, but "data": { "values": [] }, does not have any field named ts, so the encoding is undefined and no mark is drawn.

  2. The datum encoding is applied to each entry in the associated dataset, but your dataset has length 0, and so there are no entries. You can use "data": { "values": [{}] } instead.

Fixing these two issues gives this (open in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "layer": [
    {
      "data": {
        "values": [
          {"ts": "2021-11-26", "a": 0.16},
          {"ts": "2021-11-28", "a": 0.12}
        ]
      },
      "mark": {"type": "point"},
      "encoding": {
        "x": {"field": "ts", "type": "temporal"},
        "y": {"field": "a", "type": "quantitative"}
      }
    },
    {
      "data": {"values": [{}]},
      "mark": {"type": "rule", "color": "red"},
      "encoding": {"y": {"datum": 0.15, "type": "quantitative"}}
    }
  ]
}

enter image description here

Related