mattijn
10/10/2019 - 8:58 AM

Color the bars based on a threshold value

Color the bars based on a threshold value

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "width": 400,
  "height": 300,
  "layer":[
  {"data": {
    "values": [
      {"category": "A", "amount": 1.8},
      {"category": "B", "amount": 0.55},
      {"category": "C", "amount": 0.43},
      {"category": "D", "amount": 0.91},
      {"category": "E", "amount": 0.81},
      {"category": "F", "amount": 0.53},
      {"category": "G", "amount": 0.19},
      {"category": "H", "amount": 0.87}
    ]
  },
  "transform": [
    {"calculate": "datum.amount > 1 ? 'goed' : 'fout'", "as": "color"}
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "category", "type": "nominal"},
    "y": {"field": "amount", "type": "quantitative"},
    "color": {
      "field": "color", "type": "nominal",
      "scale": {"range": ["#e45755", "#ADFF2F"]},
      "legend": {"orient": "bottom", "title": null}
    }, 
    "tooltip": [
      {"field": "category", "type": "nominal"},
      {"field": "amount", "type": "quantitative"}
  ]}
  },
    {
      "data": {
        "values": [{"ThresholdValue": 1, "ThresholdLabel": "drempel"}]
      },
      "layer": [
        {
          "mark": "rule",
          "encoding": {"y": {"field": "ThresholdValue", "type": "quantitative"}}
        },
        {
          "mark": {
            "type": "text",
            "align": "right",
            "baseline": "bottom",
            "dx": -2,
            "dy": -2
          },
          "encoding": {
            "x": {"value": "width"},
            "y": {
              "field": "ThresholdValue",
              "type": "quantitative",
              "axis": {"title": "amount"}
            },
            "text": {"field": "ThresholdLabel", "type": "ordinal"}
          }
        }
      ]
    }  
  ]
}