在 vega lite 中向条形图添加渐变

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

我正在尝试向 vega lite 中的条形图添加渐变。 我已经成功地绘制了其他所有内容,但是在尝试了一些方法之后,我只是无法添加渐变。 对于未预订的情况,渐变应为白色到红色 预订时渐变应为白色到绿色

这就是我目前拥有的:

{
    "data": {
        "name": "dataset"
    },
    "transform": [
        {
            "fold": ["Booked", "Not Booked"],
            "as": ["Booking Status", "Value"]
        }
    ],
    "mark": {
        "type": "bar",
        "cornerRadiusEnd": 10
    },
    "encoding": {
        "x": {
            "field": "Event Due Date",
            "type": "ordinal",
            "timeUnit": "month",
            "title": "",
            "sort": "x"
        },
        "y": {
            "field": "Value",
            "aggregate": "sum",
            "type": "quantitative",
            "title": ""
        },
        "color": {
            "field": "Booking Status",
            "type": "nominal",
            "scale": {
                "domain": ["Booked", "Not Booked"],
                "range": ["green", "red"]
            },
            "title": "Booking Status"
        },
        "xOffset": {
            "field": "Booking Status"
        }
    }
}

我尝试添加一个在范围内停止的渐变,与色块中的比例相关。看来这是不可能的。 我尝试在顶部添加一层,但这似乎也不起作用。

json bar-chart vega-lite
1个回答
0
投票

我通常反对在条形图中使用渐变,而不是只对条形使用纯色。但如果您必须这样做,下面的代码将执行此操作(在 Vega 编辑器中打开图表)。这个想法是您需要两个层,经过过滤以显示数据的相反部分,每个层都为过滤后的数据使用正确的梯度。 (我在这里使用 Vega 编辑器的示例数据;您可以轻松地将其改编为您自己的数据。)

结果:

enter image description here

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "data/seattle-weather.csv"},
  "layer": [
    {
      "transform": [{"filter": "month(datum.date) % 2 == 0"}],
      "mark": {
        "type": "bar",
        "color": {
          "x1": 1,
          "y1": 1,
          "x2": 1,
          "y2": 0,
          "gradient": "linear",
          "stops": [
            {"offset": 0, "color": "white"},
            {"offset": 1, "color": "red"}
          ]
        }
      },
      "encoding": {
        "x": {"timeUnit": "month", "field": "date", "type": "temporal"},
        "y": {"aggregate": "mean", "field": "precipitation"}
      }
    },
    {
      "transform": [{"filter": "month(datum.date) % 2 == 1"}],
      "mark": {
        "type": "bar",
        "color": {
          "x1": 1,
          "y1": 1,
          "x2": 1,
          "y2": 0,
          "gradient": "linear",
          "stops": [
            {"offset": 0, "color": "green"},
            {"offset": 1, "color": "red"}
          ]
        }
      },
      "encoding": {
        "x": {"timeUnit": "month", "field": "date", "type": "temporal"},
        "y": {"aggregate": "mean", "field": "precipitation"}
      }
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.