如何在Vega-Lite中为特定颜色的线着色?

时间:2019-12-25 10:54:48

标签: vega-lite

VegaLite自动分配颜色。黄金的价格为蓝色,银的价格为橙色,这是错误的。

enter image description here

如何为金黄色指定明确的颜色-#F1C40F,对于银色为#95A5A6

我还想将data.values保留为下面的示例代码-作为一组单独的数组。

代码和Playground

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {
    "values": [
      {
        "dates": ["2000-01", "2000-02", "2000-03"], 
        "gold": [1, 2, 1], 
        "silver": [1.5, 1, 2]
      }
    ]
  },
  "transform": [
    {"flatten": ["dates", "gold", "silver"]},
    {"fold": ["gold", "silver"], "as": ["symbol", "price"]},
    {"calculate": "datetime(datum.dates)", "as": "dates"}
  ],
  "mark": {"type": "line", "point": {"filled": false, "fill": "white"}},
  "encoding": {
    "x": {"field": "dates", "type": "temporal", "timeUnit": "yearmonth"},
    "y": {"field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用scale.domainscale.range参数设置自定义Color Scheme

"color": {
  "field": "symbol",
  "type": "nominal",
  "scale": {"domain": ["gold", "silver"], "range": ["#F1C40F", "#95A5A6"]}
}

无论指定数据源如何,此方法都有效。

以下是应用于图表(Vega Editor)的结果:

enter image description here