Lazar Nikolov
Lazar Nikolov

Reputation: 1028

Dygraphs: part of series into separate legends

I'm trying to achieve multiple legends for one chart. For example, I've got 10 series on one graph, but I'd like 5 of them to appear in a legend left of the graph, and the other 5 in a legend on the right of the graph. We've got lots of series with different measurement units, so we'd like to separate, for example, the Percentage values on the left axis and in the left legend, the Voltage values on the right axis and in the right legend.

Is this possible?

Upvotes: 1

Views: 132

Answers (1)

danvk
danvk

Reputation: 16945

You can do this with a legendFormatter. The intent of this option is to format the standard legend (the one that appears in the top right of the chart or in the labelsDiv). But there's no reason you can't use it for side effects.

Something like this should do what you want:

function legendFormatter(data) {
  const leftDiv = document.getElementById('left');
  const rightDiv = document.getElementById('right');
  if (data.x == null) {
    // no selection
    leftDiv.textContent = '';
    rightDiv.textContent = '';
  } else {
    const percentSeries = data.series.filter(v => v.contains('Percentage'));
    const voltageSeries = data.series.filter(v => v.contains('Voltage'));

    leftDiv.innerHTML = data.xHTML + percentSeries.map(v => v.labelHTML + ': ' + v.yHTML).join(' ');
    rightDiv.innerHTML = data.xHTML + voltageSeries.map(v => v.labelHTML + ': ' + v.yHTML).join(' ');
  }
  return '';
}

There's some documentation of the data parameter here.

Upvotes: 2

Related Questions