Legends from marks

Hi everyone, glad to be joining this community around the wonderful Observable!

As a newcomer to Observable, I am struggling with legends. I understand how to put legends based on color or opacity from a dataset, as in many of the examples our there.

But is there a way to (manually?) build legends from the marks?
Concretely, how can I put legends on the following example (from @observablehq/plot-linear-regression):

Plot.plot({
  marks: [
    Plot.dot(cars, {x: "weight (lb)", y: "power (hp)", strokeOpacity: 0.5, r: 2}),
    Plot.linearRegressionY(cars, {x: "weight (lb)", y: "power (hp)", stroke: "steelblue", ci: 0.95})
  ]
})

I would like a legend that shows that:

  1. the dots are data points,
  2. the line is the regression line and
  3. the shaded regions are the 95% confidence bands for the regression line.

Thanks!

1 Like

Welcome!
I don’t think there is a way to make a legend like that, but I often use a caption to explain how to read the graph.

Plot.plot({
  marks: [
    Plot.dot(cars, {x: "weight (lb)", y: "power (hp)", strokeOpacity: 0.5, r: 2}),
    Plot.linearRegressionY(cars, {x: "weight (lb)", y: "power (hp)", stroke: "steelblue", ci: 0.95})
  ],
  caption: "The line is a regression line with shaded regions showing the 95% confidence bands."
})
1 Like

Thanks a lot for the quick reply! The caption helps a bit, but I would really prefer a legend. I wonder if I can do it with some manual javascript trickery?

Can you describe (visually) what you want to achieve? There are lots of possibilities within Plot: you could add text (even multiline text) and other marks, or even another chart as part of the main plot… you could also create a custom mark that return a foreignObject containing any type of HTML.

1 Like

Thanks! I was thinking something like this:

You can definitely just build that legend in Plot itself. I guess the following is getting kind of close, though I’m not quite sure how to generate your outlier curves off the top of my head:

The typeset mathematics is probably the trickiest part here. You can read more about that in this and that.

3 Likes

Sweet, got it!