How to Add Range (Min/Max) to Legend

Often, when I make a classed choropleth, people want to know the range (min/max) as well as the breakpoints. That is, I want to turn this:


into this:

The default for @d3/color-legend and the Observable Plot legend is to not display these end values. I hacked a very ugly workaround here using D3 to copy and add ticks: Quantile Choropleth / Evan Galloway | Observable, but I imagine there is a more elegant solution here, maybe even one using the Legend options. Any thoughts?

2 Likes

It seems to me that you should be able to specify the tickValues option. That seems to work for most continuous scales. The following gets close to what you want, for example:

Legend(
  d3.scaleSequentialQuantile(
    unemployment.map((d) => d.rate),
    d3.interpolateBlues
  ),
  {
    tickValues: d3.range(0, 1.05, 1 / 9).map((q) =>
      d3.quantile(
        unemployment.map((d) => d.rate),
        q
      )
    ),
    tickFormat: d3.format("0.1f")
  }
)

Of course, you lose the discrete steps, though.

Thanks, Mark. I had the same initial thought that tickValues would allow me to add the extent, but tickValues appears to be ignored with threshold type scales, which makes some sense since the thresholds are critically important to the legend. (You wouldn’t want a legend with numbers out of sync with the steps.)

I started tinkering with the @d3/color-legend code to allow an override, but I haven’t wrapped my head around that code yet.