plot - Vega-Lite:添加不基于字段值/自动颜色/自动形状的自定义图例

标签 plot graph legend vega-lite vega

我正在寻找一种为多字段数据输出自定义图例的方法。理想情况下,我想对我可能拥有的所有字段进行静态颜色编码(总共可能有大约 20 个),并按颜色和任意文本输出图例,或者至少输出一个字段名称。

在下面的示例中,我想要一个图例来显示“蓝色描边系列 1 红色描边系列 2”。

我很乐意展示我目前所拥有的东西,但我尝试过将“图例”放置在它可能适合的任何地方,但它没有做任何事情。

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"x": 1, "y": 10},
      {"x": 2, "y": 7},
      {"x2": 1, "y2": 11},
      {"x2": 2, "y2": 12}
    ]
  },
  "encoding": {"x": {"type": "quantitative"}, 
               "y": {"type": "quantitative"}},
  "layer": [
    {
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "x"}, 
            "y": {"field": "y"},
            "color": {"value": "blue"}
            
            }
        },
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "x2"},
            "y": {"field": "y2"},
            "color": {"value": "red"}
          }
        }
      ]
    }
  ]
}

最佳答案

Vega-Lite 中的图例是根据编码创建的,因此如果您希望显示图例,则需要构建适当的编码。对于分层图表,实现此目的的一种方法是为每个图层使用datum 编码,然后您可以构建一个自定义色标,将这些编码映射到所需的颜色。例如(open in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {
    "values": [
      {"x": 1, "y": 10},
      {"x": 2, "y": 7},
      {"x2": 1, "y2": 11},
      {"x2": 2, "y2": 12}
    ]
  },
  "encoding": {
    "x": {"type": "quantitative"},
    "y": {"type": "quantitative"},
    "color": {
      "type": "nominal",
      "scale": {"domain": ["Series1", "Series2"], "range": ["blue", "red"]}
    }
  },
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "x": {"field": "x"},
        "y": {"field": "y"},
        "color": {"datum": "Series1"}
      }
    },
    {
      "mark": "line",
      "encoding": {
        "x": {"field": "x2"},
        "y": {"field": "y2"},
        "color": {"datum": "Series2"}
      }
    }
  ]
}

enter image description here

关于plot - Vega-Lite:添加不基于字段值/自动颜色/自动形状的自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70221517/

相关文章:

python - 如何强制 matplotlib 将 x 轴上的值显示为整数

matlab - 如何在matlab中找到xlabel的实际长度或坐标

r - 当包已经使用现有标题时,如何更改 R 中的绘图标题?

r - ggplot2:如何为添加到散点图的线添加图例?

html - 图例不适合(不同的分辨率)

c++ - 使用 SFML 绘制函数

javascript - 如何正确缩放 d3 中的图表?

MATLAB - 绘制 .wav 文件的时频图

给定节点像素位置的边缘路由算法?

plot - 如何在谷歌电子表格图中编辑图例标签?