Legend options in Plot.plot?

How do I add legend options in a call to Plot.plot?

For example, I can do this:

data = FileAttachment("penguins.csv").csv({typed: true})`

and then this:

plot = Plot.plot({
  inset: 8,
  grid: true,
  color: {
    legend: "ramp",
  },
  marks: [
    Plot.dot(data, {x: "flipper_length_mm", y: "body_mass_g", stroke: "sex"})
  ]
})

And I can do this:

  plot.legend("color", {legend: "ramp", label: "Sex", width: 400})

But how do I get those legend options, {legend: "ramp", label: "Sex", width: 400}, into the initial plot?

Example notebook here: https://observablehq.com/d/548adf32637ea5d3

Add it to the color scale options like so:

plot = Plot.plot({
  inset: 8,
  grid: true,
  color: {
    legend: "ramp",
    label: "Sex",
    width: 400
  },
  marks: [
    Plot.dot(data, { x: "flipper_length_mm", y: "body_mass_g", stroke: "sex" })
  ]
})

Thanks - that works a charm.

I would suggest adding that to the docs - I couldn’t find it either on the Legends page:

or on the Scales page:

and it wasn’t obvious, at least to me, that adding a width parameter to the scale would apply to the legend for that scale as opposed to somehow affecting to the scale itself.

1 Like