向双 Y 轴条形图添加任意图例

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

我正在编写如下所示的 Vega-lite 代码。我正在尝试添加具有两个值的图例/键,例如:

Legend

尝试1要点:https://gist.github.com/woter1832/ca24c4dd3a733072239f3a22b7b012dc
Vega 编辑器
添加第 18 行 (

"color": {"field": "cost", "type": "quantitative"}
) 创建分级图例。

尝试2要点:https://gist.github.com/woter1832/eb1c820e307de8a52b00e0ba7ec4fe47
Vega 编辑器
这是正确的图例类型,但图表不正确。

Vega 编辑器
添加图例的代码:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": "container",
  "height": 550,
  "data": {
    "values": [
      {"model": "Audi", "score": 150, "cost": 4500},
      {"model": "Mercedes", "score": 75, "cost": 6000},
      {"model": "BMW", "score": 115, "cost": 5000}
    ]
  },
  "encoding": {
    "x": {"field": "model", "type": "nominal", "axis": {"labelAngle": 45, "title": "Model"}}
  },
  "layer": [
    {
      "mark": {"type": "bar", "color": "steelblue", "width":{"band": 0.75}},
      "encoding": {
        "y": {"field": "score", "type": "quantitative", "axis": {"title": "Score"}, "scale":{"rangeMax":-100}},
        "xOffset":{"value": 0}
      }
    },
    {
      "mark": {"type": "bar", "color": "orange", "width":{"band": 0.4}},
      "encoding": {
        "y": {"field": "cost", "type": "quantitative", "axis": {"title": "Cost", "orient": "right", "format": "$.0f"}},
        "xOffset":{"value": 0}
      }
    }
  ],
  "resolve": {
    "scale": {
      "y": "independent"
    }
  }
}

要点链接:https://gist.github.com/woter1832/6a9c227f9a2ae5393cbb7f6f83ed3a7f

任何帮助将不胜感激。

T.I.A.

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

enter image description here

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "width": "container",
  "height": 550,
  "data": {
    "values": [
      {"model": "Audi", "score": 150, "cost": 4500},
      {"model": "Mercedes", "score": 75, "cost": 6000},
      {"model": "BMW", "score": 115, "cost": 5000}
    ]
  },
  "encoding": {
    "x": {
      "field": "model",
      "type": "nominal",
      "axis": {"labelAngle": 45, "title": "Model"}
    }
  },
  "layer": [
    {
      "mark": {"type": "bar", "fill": "steelblue", "width": {"band": 0.75}},
      "encoding": {
        "y": {
          "field": "score",
          "type": "quantitative",
          "axis": {"title": "Score"},
          "scale": {"rangeMax": -100}
        },
        "xOffset": {"value": 0},  "color": {
          "field": "x",
          "title":"My Legend",
          "scale": {
            "domain": ["cost", "score"],
            "range": ["steelblue", "orange"]
          }
        }
      }
    },
    {
      "mark": {"type": "bar", "color": "orange", "width": {"band": 0.4}},
      "encoding": {
        "y": {
          "field": "cost",
          "type": "quantitative",
          "axis": {"title": "Cost", "orient": "right", "format": "$.0f"}
        },
        "xOffset": {"value": 0}
      }
    }
  ],
  "resolve": {"scale": {"y": "independent"}}
}
© www.soinside.com 2019 - 2024. All rights reserved.