susielu / d3-legend

A reusable d3 legend component.
http://d3-legend.susielu.com/
Apache License 2.0
727 stars 104 forks source link

Support for d3.scaleTime() #88

Closed fmannhardt closed 5 years ago

fmannhardt commented 6 years ago

The current version seems to not support D3 Time Scales as input. Only NaN and black shapes are displayed for the color legend.

Since time scales are a straightforward extension of linear scales, what would it take to support time scales?

susielu commented 5 years ago

It's a bit more tangled than that, the formatting library is different, and generating the labels requires more logic. I am not going to support this use case for now, but open to a pull request.

martingraham commented 4 years ago

It is hackable by making a linear scale from the unix timestamps of the time scale domain

i.e. where scale is the timeScale newScale = d3.scaleLinear().range(scale.range()).domain(scale.domain().map((d: Date|Moment): number => d.valueOf()))

And then using the label and labelFormat options to return these as date strings in the legend labels

 // need d3.format('.0f') otherwise the unix timestamps get turned into scientific notation strings
.labelFormat(d3.format('.0f'))
.labels (makeTimeLabels)
.scale (newScale)

makeTimeLabels is just a function that does this or similar:

  function makeTimeLabels (labelObj: any): string {
      const label: string = labelObj.generatedLabels[labelObj.i];
      return d3.utcFormat('%H:%M:%S, %a %d %B, %Y')(new Date(+label));  // utcFormat one of many time formats
  }