简体   繁体   中英

How to set different colors area chart depending on value Vega Lite

I want to create area chart in which area above y=0 will be one color anb below - another. I have a problem with setting conditional color in Vega-Lite. (I'm using guide from https://vega.github.io/vega-lite/docs/condition.html )

"color": {
      "condition": {
        "test": "datum['y'] < 0",
        "value": {
          "x1": 1,
          "y1": 1,
          "x2": 1,
          "y2": 0,
          "gradient": "linear",
          "stops": [
            {
              "offset": 0,
              "color": "white"
            },
            {
              "offset": 1,
              "color": "orange"
            }
          ]
        }
      },
      "value": {
       // otherValue
    }

Full code here:

https://codesandbox.io/s/interactive-vega-lite-bar-chart-forked-b0hnh?file=/index.html

The condition is not working on mark area . Tried the same for type bar or point and it worked. Still managed to get the gradient effect with colors red, white and orange. You can refer the below config or refer link :

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Google's stock price over time.",
  "data": {
    "values": [
      {"date": "2021-03-29", "value": -10, "rValue": 0},
      {"date": "2021-03-28", "value": -20, "rValue": 0},
      {"date": "2021-03-27", "value": 20, "rValue": 0},
      {"date": "2021-03-26", "value": 40, "rValue": 0},
      {"date": "2021-03-25", "value": 35, "rValue": 0}
    ]
  },
  "width": 400,
  "height": 200,
  "mark": {"type": "area"},
  "encoding": {
    "x": {
      "field": "date",
      "type": "temporal",
      "axis": {"format": "%d/%m/%Y", "labelPadding": 10}
    },
    "y": {"field": "value", "type": "quantitative"},
    "fill": {
      "value": {
        "gradient": "linear",
        "stops": [
          {"offset": 0, "color": "red"},
          {"offset": 0.5, "color": "white"},
          {"offset": 1, "color": "orange"}
        ]
      }
    }
  },
  "config": {}
}

Also, I tried your mark area with a simple configuration and that didn't work. I have created a config having bar which works properly with condition but if the same is changed to area than it does not work.

One way to do this is to overlay a separate layer.

在此处输入图像描述

However I'm not sure how to color the bit before the first negative value.

Open the Chart in the Vega Editor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM