I am trying to add a legend to the d3.js example named
Line chart with zoom in d3.js
1°) I added the script:
// Add legend rectangle
line.append('rect')
.attr('x', width - 80)
.attr('y', 90)
.attr('width', 10)
.attr('height', 10)
.style('fill', "steelblue");
// Add legend text
line.append("text")
.attr('x', width - 65)
.attr('y', 100)
.text('Blue line');
2°) I reduced the x axis in the existing code to separate the legend and the chart:
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) { return d.date; }))
.range([ 0, width - 100 ]);
Unfortunately, the legend merges with the chart when I zoom! How to solve this?
2
Answers
Many thanks for this good idea, Mark. I applied it to my multi line chart and it works :-)
The example you are following follows a frequently used coding convention in
d3
of separating out the "drawing area" of the chart around a series of margins.Instead of attempting to adjust the x axis scale the way you are doing, I would increase the right margin and move your legend there.
Here’s an example: