如何对值进行排序并使鼠标悬停交互?

时间:2020-08-17 06:56:23

标签: vega-lite vega

我已经用代码构建了水平条形图

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.4.json",
  "description": "Bar chart with text labels. Apply scale padding to make the frame cover the labels.",
  "data": {
      "values": [
      {"Metrics": "A1", "Percentage": 0.79},
      {"Metrics": "A2", "Percentage": 0.0399},
      {"Metrics": "A3", "Percentage": 0.9868},
      {"Metrics": "A4", "Percentage": 0.0536},
      {"Metrics": "A5", "Percentage": 0.9412},
      {"Metrics": "A6", "Percentage": 0.0536}
      ]
  },
  "encoding": {
    "y": {"field": "Metrics", "type": "nominal"},
    "x": {"field": "Percentage", "type": "quantitative", "scale": {"padding": 10}}
  },
  "layer": [{
    "mark": "bar"
  }, {
    "mark": {
      "type": "text",
      "align": "left",
      "baseline": "middle",
      "dx": 3
    },
    "encoding": {
      "text": {"field": "Percentage", "type": "quantitative"}
    }
  }]
}

我得到的情节像 enter image description here

酒吧不整齐 我可以知道如何对值进行排序和绘图,是否可以使鼠标悬停并查看值

1 个答案:

答案 0 :(得分:1)

排序

您可以将排序属性添加到encoding.y,将其值设置为-x(降序),然后使其如下所示:

"encoding": {
  "y": {
    "field": "Metrics",
    "type": "nominal",
    "sort": "-x"
  },

对于递增值,请将sort属性设置为x

文档:https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding

鼠标悬停时的值

您可以在tooltip节中添加一个encoding子节,并添加多个数据属性,如下所示:

"tooltip": [
  {
    "field": "Metrics",
    "type": "nominal"
  }, {
    "field": "Percentage",
    "type": "quantitative"
  }
]

文档:https://vega.github.io/vega-lite/docs/tooltip.html

更新的编码部分

"encoding": {
  "y": {
    "field": "Metrics",
    "type": "nominal",
    "sort": "-x"
  },
  "x": {
    "field": "Percentage",
    "type": "quantitative",
    "scale": {"padding": 10}
  },
  "tooltip": [{
    "field": "Metrics",
    "type": "nominal"
  }, {
    "field": "Percentage",
    "type": "quantitative"
  }
  ]
}

link以更新规范