Search code examples
vega-litevega

How to sort the values and make interactive with mousehover?


I have built the horizontal bar chart with code

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

I get the plot like enter image description here

The bars are not in order May I know how to sort the values and plot and is it possible to make mousehover and see the values


Solution

  • Sorting

    You can add a sort attribute to encoding.y, set its value as -x (descending) and make it as below:

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

    For ascending values, set sort attribute to x

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

    Values on mousehover

    You can add a tooltip subsection in encoding section and add multiple data attributes as below:

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

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

    Updated encoding section

    "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 to updated spec