Top-K Plot Example

A plot of the top-k film directors by aggregate worldwide gross. Performs an aggregation of all directors, ranks them, and filters to only the top results. See the Top-K Plot With Others example to see a variant that combines all remaining directors into an “Others” category.

Vega JSON Specification <>

{
  "$schema": "https://vega.github.io/schema/vega/v3.0.json",
  "width": 500,
  "height": 410,
  "padding": 5,
  "autosize": "fit",

  "signals": [
    {
      "name": "k", "value": 20,
      "bind": {"input": "range", "min": 10, "max": 30, "step": 1}
    },
    {
      "name": "op", "value": "average",
      "bind": {"input": "select", "options": ["average", "median", "sum"]}
    },
    {
      "name": "label",
      "value": {"average": "Average", "median": "Median", "sum": "Total"}
    }
  ],

  "title": {
    "text": {"signal": "'Top Directors by ' + label[op] + ' Worldwide Gross'"},
    "anchor": "start"
  },

  "data": [
    {
      "name": "directors",
      "url": "data/movies.json",
      "transform": [
        {
          "type": "filter",
          "expr": "datum.Director != null && datum.Worldwide_Gross != null"
        },
        {
          "type": "aggregate",
          "groupby": ["Director"],
          "ops": [{"signal": "op"}],
          "fields": ["Worldwide_Gross"],
          "as": ["Gross"]
        },
        {
          "type": "window",
          "sort": {"field": "Gross", "order": "descending"},
          "ops": ["row_number"], "as": ["rank"]
        },
        {
          "type": "filter",
          "expr": "datum.rank <= k"
        }
      ]
    }
  ],

  "marks": [
    {
      "type": "rect",
      "from": {"data": "directors"},
      "encode": {
        "update": {
          "x": {"scale": "x", "value": 0},
          "x2": {"scale": "x", "field": "Gross"},
          "y": {"scale": "y", "field": "Director"},
          "height": {"scale": "y", "band": 1}
        }
      }
    }
  ],

  "scales": [
    {
      "name": "x",
      "type": "linear",
      "domain": {"data": "directors", "field": "Gross"},
      "range": "width",
      "nice": true
    },
    {
      "name": "y",
      "type": "band",
      "domain": {
        "data": "directors", "field": "Director",
        "sort": {"op": "max", "field": "Gross", "order": "descending"}
      },
      "range": "height",
      "padding": 0.1
    }
  ],

  "axes": [
    {
      "scale": "x",
      "orient": "bottom",
      "format": "$,d",
      "tickCount": 5
    },
    {
      "scale": "y",
      "orient": "left"
    }
  ]
}