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

How to sort the values and make interactive with mousehover?

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

{
  "$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"}
    }
  }]
}

我得到了这样的情节

条形不规则 我可以知道如何对值进行排序和绘制吗,是否可以使鼠标悬停并查看值

正在排序

你可以给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

鼠标悬停时的值

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

"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 更新规范