Custom tooltip text and keeping stroke colour

I am trying to add some custom text to a tooltip based on this documentation.

Using penguins I am uncertain how to retain that nice little coloured box that comes by default. Somehow I seem to lose it when I change the text. The notebook is here: Tooltips / Sam Albers | Observable

But here is the code where I lose it:

Plot.plot({
  grid: true,
  marks: [
    Plot.dot(penguins, {
      x: "bill_length_mm",
      y: "flipper_length_mm",
      stroke: "sex"
    }),
    Plot.tip(penguins, Plot.pointer({
      x: "bill_length_mm",
      y: "flipper_length_mm",
      stroke: "sex",
      filter: (d) => d.sex,
      title: (d) => ` sex: ${d.sex} \n year: ${d.year}`
    }))
  ]
})

Any suggestions are much appreciated.

Yes. Currently the only way to have this color swatch is to use the default channels as tip contents, and not the title. You can however add more channels to the tip, like so:

Plot.tip(penguins, Plot.pointer({
  x: "bill_length_mm",
  y: "flipper_length_mm",
  stroke: "sex",
  filter: (d) => d.sex,
  channels: {year: "year"}
}))

See Custom format for the tip mark? · Issue #1612 · observablehq/plot · GitHub

Ah gotcha. So using channels there is no current way to modify the category label? It just takes the column name?

It takes the color scale label, which defaults to the column name—but you can change it by specifying it explicitly, for example:

Plot.plot({
  color: { label: "My custom label" },
  marks: […]
})

Oh that’s super useful but I was referring to the year variable.

channels: {
 year: {
   value: {
     transform: (data) => data.map((d) => d.year),
     label: "My custom year label"
   }
 }

shorter, but maybe more arcane:

channels: {year: Object.assign((d) => d.year, {label: "My custom year label"})}

Note that it would be tempting to have the following—but it doesn’t work currently, since the label must be on the “value”:

channels: {year: {value: "year", label: "My custom year label"}}
1 Like

See Channel label option · Issue #1733 · observablehq/plot · GitHub

1 Like

I forgot to mention that you can give the channel any name you want (provided the accessor is not a string which would create a label… ah, defaults and priorities):

channels: {["My custom year label"]: d => d.year}