mattijn
10/8/2019 - 8:41 PM

Vega Bar Chart With Two Vertical Rules.

Vega Bar Chart With Two Vertical Rules.

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 400,
  "height": 200,
  "data": [
    {
      "name": "table",
      "values": [
        {"category": "A", "amount": 28},
        {"category": "B", "amount": 55},
        {"category": "C", "amount": 43},
        {"category": "D", "amount": 91},
        {"category": "E", "amount": 81},
        {"category": "F", "amount": 53},
        {"category": "G", "amount": 19},
        {"category": "H", "amount": 87}
      ],
      "transform": [
        {"type": "extent", "field": "amount", "signal": "sy_values"}
      ]
    }
  ],
  "signals": [{"name": "ref_line", "value": 40}],
  "scales": [
    {
      "name": "xscale",
      "type": "band",
      "domain": {"data": "table", "field": "category"},
      "range": "width",
      "padding": 0.05,
      "round": true
    },
    {
      "name": "yscale",
      "domain": {"data": "table", "field": "amount"},
      "nice": true,
      "range": "height"
    }
  ],
  "axes": [
    {"orient": "bottom", "scale": "xscale"},
    {"orient": "left", "scale": "yscale"}
  ],
  "marks": [
     {
      "type": "rect",
      "encode": {
        "update": {
          "y": {"scale": "yscale", "signal": "min(0,sy_values[0])"},
          "y2": {"scale": "yscale", "signal": "ref_line"},
          "x": {"value": 0},
          "x2": {"signal": "width"},
          "fill": {"value": "red"},
          "opacity":{"value":0.4}
        }
      }
    },
    {
      "type": "rect",
      "encode": {
        "update": {
          "y": {"scale": "yscale", "signal": "ref_line"},
          "y2": {"scale": "yscale", "signal": "sy_values[1]"},
          "x": {"value": 0},
          "x2": {"signal": "width"},
          "fill": {"value": "green"},
          "opacity":{"value":0.4}
        }
      }
    },    
    {
      "type": "rect",
      "from": {"data": "table"},
      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "category"},
          "width": {"scale": "xscale", "band": 1},
          "y": {"scale": "yscale", "field": "amount"},
          "y2": {"scale": "yscale", "value": 0}
        },
        "update": {
          "fill": {"value": "steelblue"},
          "tooltip": {"signal": "datum"}
        },
        "hover": {"fill": {"value": "lightblue"}}
      }
    }
  ]
}