Search code examples
vega-lite

spacing around visualizations in Vega-Lite


I know how to control the spacing of elements within a visualization, and I know how to control the width and height of the visualization. However, is it possible to control the spacing between the visualization and other elements, such as the title or legend?


Solution

  • To customize titles, you can use an object instead of a string. You can learn more about the available options in the docs at https://vega.github.io/vega-lite/docs/title.html.

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v3.json",
      "description": "A simple bar chart with embedded data.",
      "title": {
        "text": "This is an awesome Chart!",
        "offset": 20
      },
      "data": {
        "values": [
          {"a": "A","b": 28}, {"a": "B","b": 55}, {"a": "C","b": 43},
          {"a": "D","b": 91}, {"a": "E","b": 81}, {"a": "F","b": 53},
          {"a": "G","b": 19}, {"a": "H","b": 87}, {"a": "I","b": 52}
        ]
      },
      "mark": "bar",
      "encoding": {
        "x": {"field": "a", "type": "ordinal"},
        "y": {"field": "b", "type": "quantitative"}
      }
    }
    

    If you want to make your chart more compact, you can also use a negative offset.

    enter image description here

    You can customize legends similarly.

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v3.json",
      "data": {
        "url": "data/cars.json"
      },
      "mark": "point",
      "encoding": {
        "x": {
          "field": "Horsepower",
          "type": "quantitative"
        },
        "y": {
          "field": "Miles_per_Gallon",
          "type": "quantitative"
        },
        "color": {
          "field": "Origin",
          "type": "nominal",
          "legend": {
            "labelOffset": 30,
            "titleAnchor": "end",
            "offset": 30
          }
        }
      }
    }
    

    enter image description here