legend placement options

Is it possible to move a legend inside the plot area? For example, given

plot = Plot.plot({
  color: {legend: true, domain: ['FEMALE', 'MALE', null], range: ["red", "blue", "green"]},
  marks: [
    Plot.dot(data, {x: "flipper_length_mm", y: "body_mass_g", fill: "sex"})
  ]
})

can I move the color legend to the bottom right of the plot area?

More generally, what strategies do folks use to draw a color legend inside a plot area?

Example notebook: legend placement / Ben Zipperer | Observable

1 Like

I donā€™t think that thereā€™s a way to control the placement of legends, but there are ways of doing it manually. Legends can be created separately using the Plot.legend() function. You can then place that inside a div and move around using CSS.

1 Like

I didnā€™t see anything about moving plot legend location in the documentation either. You can move the plot legend to the right easily enough with the CSS float property. I think itā€™s easier to move the legend below the plot by switching their positions in the output. You can accomplish that with the following code in a separate cell:

move = {
  d3.select(plot)
    .select("div")
    .raise() // Places swatch below the plot
    .style("float", "right"); // Floats the swatch on the right.
}

Here that is in action:

4 Likes