根据线性回归结果动态改变 vega-lite 面积图的颜色

问题描述 投票:0回答:1

我们有时间序列数据,并叠加线性回归来指示趋势
enter image description here

现在,如果趋势正在下降,我们想将其染成红色,如下所示
enter image description here

参见示例

我们尝试了各种参数方法,但未能使颜色依赖于趋势。我们的方法重点是获取斜率并检查它是正值还是负值。

json charts visualization vega-lite
1个回答
0
投票

给你。我会让你修复渐变。

enter image description here

enter image description here

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "params": [
    {
      "name": "slope",
      "expr": " (data('data_1')[1]['date']-data('data_1')[0]['date'])/(data('data_1')[1]['value']-data('data_1')[0]['value']) "
    },
    {
      "name": "red",
      "expr": "{gradient: 'linear', stops: [{offset: 0, color: 'red'}, {offset: 1, color: 'red'}]}"
    },
    {
      "name": "green",
      "expr": "{gradient: 'linear', stops: [{offset: 0, color: 'green'}, {offset: 1, color: 'green'}]}"
    }
  ],
  "data": {
    "values": [
      {"date": "2023-03-31", "value": 80},
      {"date": "2023-06-30", "value": 78},
      {"date": "2023-09-31", "value": 81},
      {"date": "2023-12-31", "value": 75},
      {"date": "2024-03-31", "value": 72},
      {"date": "2024-06-30", "value": 75},
      {"date": "2024-09-31", "value": 70}
    ]
  },
  "encoding": {
    "x": {"field": "date", "type": "temporal"},
    "y": {"field": "value", "type": "quantitative"}
  },
  "layer": [
    {
      "mark": {
        "type": "line",
        "color": "rgba(0,0,0,0.5)",
        "strokeWidth": 2,
        "clip": true
      },
      "transform": [{"regression": "value", "on": "date"}]
    },
    {
      "mark": {
        "type": "area",
        "clip": true,
        "line": {"color": {"expr": "slope>0?'red':'green'"}, "strokeWidth": 4},
        "color": {"expr": "slope>0?red:green"}
      }
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.