根据正/负x轴值渲染不同的填充/描边颜色

时间:2019-09-26 14:00:19

标签: data-visualization vega

我正在尝试编写一些用于风险/机会分析的图表。您输入了4个值:

  • PreConsequence和PostConsequence(整数介于-4到+4之间)
  • 喜欢前和喜欢后(int介于0到4之间)

它使用图表将其可视化如下:

Risk / Opportunity Analysis Glyphs

阴影填充呈现 Pre 值,而笔触呈现 Post 值。 左象限中的几何表示风险,应为红色,右象限中的几何表示为机会,应为绿色。

我正在努力寻找如何检查负面结果值并相应分配颜色的方法。我认为这将在下面的代码的最后两行中完成:

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "width": 500,
  "height": 250,

  "data": [
    {
      "name": "table",
      "values": [
        {"C": -4,  "L": 0, "f":"Pre"}, {"C": 0,  "L": 4, "f":"Pre"}, 
        {"C": 0,  "L": 2, "f":"Post"}, {"C": -1,  "L": 0, "f":"Post"}
      ]
    }
  ],

  "scales": [
    {
      "name": "xscale",
      "type": "linear",
      "range": "width",
      "nice": true,
      "zero": true,
      "domain": {"data": "table", "field": "C"},
      "domainMax": 4,
      "domainMin": -4
    },
    {
      "name": "yscale",
      "type": "linear",
      "range": "height",
      "domain": {"data": "table", "field": "L"},
      "domainMax": 4,
      "domainMin": 0
    },
    {
      "name": "color",
      "type": "ordinal",
      "range":"ordinal",
      "domain": {"data": "table", "field": "f"}
    }
  ],

  "axes": [
    {"orient": "bottom", "scale": "xscale", "tickCount": 10 },
    {"orient": "left", "scale": "yscale", "tickCount": 5, "offset": -250 }
  ],

  "marks": [
    {
      "type": "group",
      "from": {
        "facet": {
          "name": "series",
          "data": "table",
          "groupby": "f"
        }
      },
    "marks": [
    {
      "type": "area",
      "from": {"data": "series"},
      "encode": {
        "enter": {
          "x": {"scale": "xscale", "field": "C" },
          "y": {"scale": "yscale", "field": "L"},
          "y2": {"scale": "yscale", "value": 0 }, 
          "fillOpacity": [{ "test": "indata('series', 'f', 'Pre')", "value": 0.3 }, {"value": 0}],
          "strokeWidth": [{ "test": "indata('series', 'f', 'Pre')", "value": 0 }, {"value": 2}],
          "fill": [{ "test": "indata('series', 'f', 'Pre')", "value": "red" }, {"value": "red"}],
          "stroke": [{ "test": "indata('series', 'f', 'Pre')", "value": "red" }, {"value": "red"}]
        }        
      }
    }
  ]
    }
  ]
}

有人可以给我一些有关如何测试数据值并相应地设置填充和描边颜色的提示吗?

谢谢

1 个答案:

答案 0 :(得分:1)

Vega信号可用于根据数据值有条件地绘制颜色。

在给定的Vega规范中,如果数据也具有正象限C值,则像这样更改fill属性应该可以达到预期的效果。

          "fill": { "signal": "datum.C > 0 ? 'green': 'red'"},