Labeled Scatter Plot Example

A scatter plot of motion pictures, showing Rotten Tomatoes Ratings versus IMDB Ratings. The Vega label transform automatically labels points without overlapping any marks.

Vega JSON Specification <>

{
  "$schema": "https://vega.github.io/schema/vega/v5.json",
  "description": "A labeled scatter plot of films showing Rotten Tomatoes ratings versus IMDB ratings.",
  "padding": 5,
  "width": 800,
  "height": 600,
  "autosize": "pad",

  "data": [
    {
      "name": "movies",
      "url": "data/movies.json",
      "transform": [
        {
          "type": "filter",
          "expr": "datum['Rotten Tomatoes Rating'] != null && datum['IMDB Rating'] != null"
        }
      ]
    },
    {
      "name": "fit",
      "source": "movies",
      "transform": [
        {
          "type": "regression",
          "method": "quad",
          "x": "Rotten Tomatoes Rating",
          "y": "IMDB Rating",
          "as": ["u", "v"]
        }
      ]
    }
  ],

  "scales": [
    {
      "name": "x",
      "type": "linear",
      "domain": {"data": "movies", "field": "Rotten Tomatoes Rating"},
      "range": "width"
    },
    {
      "name": "y",
      "type": "linear",
      "domain": {"data": "movies", "field": "IMDB Rating"},
      "range": "height"
    }
  ],

  "axes": [
    {"orient": "left", "scale": "y", "title": "IMDB Rating"},
    {"orient": "bottom", "scale": "x", "title": "Rotten Tomatoes Rating"}
  ],

  "marks": [
    {
      "name": "points",
      "type": "symbol",
      "from": {"data": "movies"},
      "encode": {
        "enter": {
          "x": {"scale": "x", "field": "Rotten Tomatoes Rating"},
          "y": {"scale": "y", "field": "IMDB Rating"},
          "size": {"value": 25},
          "fillOpacity": {"value": 0.5}
        }
      }
    },
    {
      "name": "trend",
      "type": "line",
      "from": {"data": "fit"},
      "encode": {
        "enter": {
          "x": {"scale": "x", "field": "u"},
          "y": {"scale": "y", "field": "v"},
          "stroke": {"value": "firebrick"}
        }
      }
    },
    {
      "type": "text",
      "from": {"data": "points"},
      "encode": {
        "enter": {
          "text": {"field": "datum.Title"},
          "fontSize": {"value": 8}
        }
      },
      "transform": [
        {
          "type": "label",
          "avoidMarks": ["trend"],
          "anchor": ["top", "bottom", "right", "left"],
          "offset": [1],
          "size": {"signal": "[width + 60, height]"}
        }
      ]
    }
  ]
}