Nexter1
Nexter1

Reputation: 23

How to implement rules to color range in vega lite?

In the below Vega-Lite example, I tweaked the color scale in the encoding to be a range of red, white, and green. However, I would like to change how the scale is bound to the values. For example, the values that fall between the min value and 16 would go from red to white (heatmap style), and then the values between 16 and the max value go from white to green.

I also included a screenshot of what I'm trying to achieve. Thank you for any help!

This is what I'm going for, zero is the static middle point with no negative values showing with any green and no positive values with any red

Vega-Lite Editor Link

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
      "url": "data/seattle-weather.csv"
  },
  "title": "Daily Max Temperatures (C) in Seattle, WA",
  "config": {
      "view": {
          "strokeWidth": 0,
          "step": 13
      },
      "axis": {
          "domain": false
      }
  },
  "mark": "rect",
  "encoding": {
      "x": {
          "field": "date",
          "timeUnit": "date",
          "type": "ordinal",
          "title": "Day",
          "axis": {
              "labelAngle": 0,
              "format": "%e"
          }
      },
      "y": {
          "field": "date",
          "timeUnit": "month",
          "type": "ordinal",
          "title": "Month"
      },
      "color": {
          "field": "temp_max",
          "aggregate": "max",
          "type": "quantitative",
          "scale": {
            "range": [
              "red",
              "white",
              "green"              
            ]
          },
          "legend": {
              "title": null
          }
      }
  }
}

Upvotes: 1

Views: 1168

Answers (1)

davidebacci
davidebacci

Reputation: 30174

Do you mean something like this? You can tweak the gradient boundaries using domainMin, Mid and Max. enter image description here

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/seattle-weather.csv"},
  "title": "Daily Max Temperatures (C) in Seattle, WA",
  "config": {"view": {"strokeWidth": 0, "step": 13}, "axis": {"domain": false}},
  "mark": "rect",
  "encoding": {
    "x": {
      "field": "date",
      "timeUnit": "date",
      "type": "ordinal",
      "title": "Day",
      "axis": {"labelAngle": 0, "format": "%e"}
    },
    "y": {
      "field": "date",
      "timeUnit": "month",
      "type": "ordinal",
      "title": "Month"
    },
    "color": {
      "field": "temp_max",
      "aggregate": "max",
      "type": "quantitative",
      "scale": {
        "range": ["red", "white", "green"],
        "interpolate": "cubehelix",
        "domainMax": 40,
        "domainMid": 16,
        "domainMin": 0
      },
      "legend": {"title": null}
    }
  }
}

Upvotes: 1

Related Questions