andredumas / techan.js

A visual, technical analysis and charting (Candlestick, OHLC, indicators) library built on D3.
http://techanjs.org/
MIT License
2.4k stars 537 forks source link

Add legend to the chart #50

Open sf-wind opened 9 years ago

sf-wind commented 9 years ago

When a chart has several moving averages, it is difficult to separate them. It would be nice to add a legend (with color) to indicate which moving average is which.

Also, with crosshair, it would be nice to to show the value of the moving average in the legend.

Is this in the roadmap? Thanks.

andredumas commented 9 years ago

Definitely on the roadmap, although this is about as far is i've got...

If you can't wait, I've seen some users use an off the shelf tooltip/hint library. Or you could roll your own, should be straight forward. Crosshair events emit enough information for you to determine which index is displayed. See example: http://bl.ocks.org/andredumas/045f550b72ad46301130

It could be something like:

function move(coords) {
  var index = financetime.invertToIndex(coords[0])
  // Map the index to your calculated moving average. Set the legend data
  var legendSelection = d3.selectAll('text.legend').data(smaArrays.map(function(d) { 
    // smaArrays is an array of arrays
    return d[index].value;  // Take into account SMA preroll when converting index to value
  });

  legendSelection.enter()
    .append('text')
      .classed(function(d, i) { return 'legend sma-' + i; }); // define classes to match SMA colors

  legendSelection.text(function(d) { return 'SMA: ' + d; });
}

crosshair.on("move", move);

BTW I've jotted this down off the top of my head don't expect it to work, but it could be a start.