How to bottom middle align a legend in Vega Lite?
Asked Answered
C

2

2

In Vega Lite, I am trying to align my legend to the middle of this chart. I need something like an anchor parameter for the legend, but I can only find titleAnchor.

Chart with Legend

"legend": {
        "title": "Signed NDA",
        "orient": "bottom",
        "titleAnchor": "middle"
      }

This is how my legend looks right now. Anyone know how to do this?

Cabana answered 17/6, 2020 at 2:5 Comment(0)
M
7

This is actually possible within Vega 5.0, legend layout property, by setting the anchor property to "middle", in the legend's layout config.

Providing layout doesn't seem to be directly supported by Vega-Lite yet, but it is possible to propagate a layout definition from Vega-Lite to Vega.
Following Jake's answer, in Vega-Lite editor:

{
  "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"}
  },
  "height": 300,
  "width": 400,
  
  "config": {
    "legend": {"orient": "bottom", "layout": {"bottom": {"anchor": "middle"}}}
  }
}

Specifying the config at the end basically allows you to customize how the orient "bottom" should look.

enter image description here

Maggoty answered 13/1, 2021 at 13:13 Comment(1)
Note: some as of you may find, "react-vega" does not like the typings in Typescript. As such, I had to cast the code as follows layout: { bottom: { anchor: "middle" } } as LegendLayout as any, just in-case people wander here with Typescript/React in mindLanie
S
2

There is no option to anchor the legend in the bottom center, but you can set orient: "none" and use the legendX and legendY properties to locate it exactly where you would like. For example (vega editor):

{
  "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": {
        "orient": "none",
        "direction": "horizontal",
        "legendX": 120,
        "legendY": 340,
        "title": null
      }
    }
  },
  "height": 300,
  "width": 400
}

enter image description here

Sapphire answered 17/6, 2020 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.