How to avoid overlapping and stack long text legends in D3 graph? - javascript

I have D3 graph base on Multi-line graph 3 with v7: Legend, this sample contains few and shorts legends for the graph. In my sample I want to increase the length for legends and stack the data if is necessary, I want to avoid overlapping in the legends,
https://bl.ocks.org/d3noob/d4a9e3e45094e89808095a47da19808d
dataNest.forEach(function(d,i) {
svg.append("path")
.attr("class", "line")
.style("stroke", function() { // Add the colours dynamically
return d.color = color(d.key); })
.attr("d", priceline(d.value));
// Add the Legend
svg.append("text")
.attr("x", (legendSpace/2)+i*legendSpace) // space legend
.attr("y", height + (margin.bottom/2)+ 5)
.attr("class", "legend") // style the legend
.style("fill", function() { // Add the colours dynamically
return d.color = color(d.key); })
.text(d.key);
});

There are two possible solutions I can think of, shown in this JSFiddle.
First, if it is acceptable that the legend is not part of the svg, then realize the legend with a simple unordered list in a container next to the svg. This is probably the best when there is a varying number of legend entries and there are no restrictions considering the styling via css. The browser takes care of varying lengths and does an automatic line break.
Second, if the legend has to be a part of the svg, one can use the getBBox()-method that determines the coordinates of the smallest rectangle around an object inside an svg.
In a first step select all the legend entries that have been rendered and get the bounding boxes:
const bbox = svg.selectAll(".legend")
.nodes()
.map(legend_entry => legend_entry.getBBox());
With this array and the width of the svg, we can calculate the positions for each legend entry:
bbox.reduce((pos, box) => {
let left, right, line;
if (pos.length === 0) {
left = 0;
line = 1;
} else {
/* The legend entry starts where the last one ended. */
left = pos[pos.length - 1].right;
line = pos[pos.length - 1].line;
}
/* Cumulative width of legend entries. */
right = left + box.width;
/* If right end of legend entry is outside of svg, make a line break. */
if (right > svg_width) {
line = line + 1;
left = 0;
right = box.width;
}
pos.push({
left: left,
right: right,
line: line,
});
return pos;
}, []);
Margins and paddings have to be included manually in the calculation of the positions. Of course, one could obtain the maximum width of all legend entries and make them all the same width with center alignment as in the d3noob example.
In the JSFiddle, I realized this repositioning by first rendering a hidden legend and then an additional one that is visible. It is of course possible to use only one legend, but I would not to take any chances that the process of repositioning is visible in the rendered document.

Related

D3 Adding dots to dynamic line chart

I have a scrolling line chart that is being updated in realtime as data comes in. Here is the js fiddle for the line chart. https://jsfiddle.net/eLu98a6L/
What I would like to do is replace the line with a dot graph, so each point that comes in would create a dot, and the scrolling feature is maintained.This is the type of chart I would like to create dow jones dot graph and ultimately I would like to remove the line underneath.
This is the code I have used to try and add dots to my graph.
g.append("g")
.selectAll("dot")
.data(4)
.enter("circle")
.attr("cx", "2")
.attr("cy", "2");
So far I haven't had any success. I'm very new to d3, so any help is appreciated. Thanks!
Based on your code an approach for this can be :
var circleArea = g.append('g'); /* added this to hold all dots in a group */
function tick() {
// Push a new data point onto the back.
data.push(random());
// Redraw the line.
/* hide the line as you don't need it any more
d3.select(this)
.attr("d", line)
.attr("transform", null);
*/
circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove.
/* this add dots based on data */
circleArea.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('r',3) // radius of dots
.attr('fill','black') // color of dots
.attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';});
/* here we can animate dots to translate to left for 500ms */
circleArea.selectAll('circle').transition().duration(500)
.ease(d3.easeLinear)
.attr('transform',function(d,i){
if(x(i )<=0) { // this makes sure dots are remove on x=0
d3.select(this).remove();
}
return 'translate('+x(i-1)+','+y(d)+')';
});
/* here is rest of your code */
// Slide it to the left.
d3.active(this)
.attr("transform", "translate(" + x(-1) + ",0)")
.transition()
.on("start", tick);
// Pop the old data point off the front.
data.shift();
}
See it in action : https://codepen.io/FaridNaderi/pen/weERBj
hope it helps :)

Displaying labels on horizontal chart with d3.js

I'm creating a simple chart with d3.js using the following code. Now suppose the var data is properly formatted (ex. "[20,15,15,40,10]"), the horizontal chart displays properly but I'd like to add some labels on the left and I'm a bit overwhelmed by d3.js . I was trying to insert an extra div containing the label before every other div representing and showing the data, but I can't understand how or if that's the proper way.
The result should look something like:
Label 1 |=============================40%==|
Label 2 |=================30%==|
Label 3 |======15%==|
and so on. The bars display just fine, but how do I add the labels on the left ? This is the piece of script that displays the bars (given a div with id 'chart' and the proper css).
chart = d3.select('#chart')
.append('div').attr('class', 'chart')
.selectAll('div')
.data(data).enter()
.append('div')
.transition().ease('elastic')
.style('width', function(d) { return d + '%'; })
.text(function(d) { return d + '%'; });
You'll find a working example here . So, how do I add labels on the left of every bar so that the user knows what every bar represents ?
I think your idea of appending a <div> containing a label before each bar is reasonable. To do so, you first need to append a <div> for each bar, then append a <div> containing the label, and finally append a <div> containing the bars. I've updated your example with a JSFiddle here, with the Javascript code below (some changes were also required to the CSS):
// Add the div containing the whole chart
var chart = d3.select('#chart').append('div').attr('class', 'chart');
// Add one div per bar which will group together both labels and bars
var g = chart.selectAll('div')
.data([52,15,9,3,3,2,2,2,1,1]).enter()
.append('div')
// Add the labels
g.append("div")
.style("display", "inline")
.text(function(d, i){ return "Label" + i; });
// Add the bars
var bars = g.append("div")
.attr("class", "rect")
.text(function(d) { return d + '%'; });
// Execute the transition to show the bars
bars.transition()
.ease('elastic')
.style('width', function(d) { return d + '%'; })
Screenshot of JSFiddle output

Adding a span icon to a D3 bar chart

I'm working on a fairly basic bar chart where I'm trying to have a span icon that appears, anchored at the start of each bar. Which icon appears is dependent on the class of the bar. For example, if the bar is blue, I want a certain icon vs. if the bar is red.
I've appended and added the span which shows up in the console, but is not actually appearing any where in the chart.
I have the icons stored as spans in my css, one for each version of the value name that gets plugged in.
I've tried a variety of selections, ordering, etc. But can't get it to stick.
var bars = svg.selectAll('.bar')
.data(data)
.enter().append('g')
.attr('class', 'bar');
bars.append('rect')
var icons = svg.selectAll('rect')
.data(data)
.enter().append("span")
.attr("class", function(d, i) {
return "icon-" + d.value + "-right";
})
.attr('dx', -6)
.attr('dy', (bar_height / 2) +5)
.attr('text-anchor', 'start');
You should use foreignObject element to insert HTML into SVG.
Like so:
var icons = svg.selectAll('foreignObject').data(data);
icons.enter().append("foreignObject")
.attr("class", function(d) { return "icon-" + d.value + "-right"; })
.append("xhtml:body")
.append("xhtml:span");
Also you can use text element to add icons to the SVG:
var icons = svg.selectAll('text').data(data);
icons.enter().append("text")
.html("&#xf00d") // utf-8 character for the icon

Adding Object with Transition in D3.js after Zooming

In the d3.js example, the goal is to change the X & Y scales to reveal a newly added circle which is added offscreen.
Currently, if you were to change the zoom scale, then click on the button to add a new circle, the zoom level suddenly resets to 1. Now dragging the view will cause the zoom scale to become correct again, which is the same zoom scale right before adding the circle.
However this problem goes away if you change redrawWithTransition() on line 123 to redraw() which removes the transitions.
Everything works fine if you add the circle without first zooming.
Why do we have to drag the view again to get the correct zoom scale back? How can we avoid having to do this additional drag and still use transitions in redrawWithTransition()? Thank you!!
Jsfiddle: http://jsfiddle.net/NgWmU/
Because panning again after adding the circle solves the problem, I tried calling redraw() at the end but theres no difference! Is the panning/zooming triggering something else in addition to redraw()?
Jsfiddle: http://jsfiddle.net/NgWmU/2/
First the user zooms/pans around and ends up with a view like in figure A. Next the new circle is added and we should get figure C, but instead we get figure B where the user's current translate/zoom is changed significantly.
Another case
If the user pan/zoom to a view similar to the top figure, adding the new circle should reposition the existing circles slightly, but instead the entire view is reset.
Was thinking about something like:
// Copy existing domains
var xMinOld = xMin,
xMaxOld = xMax,
yMinOld = yMin,
yMaxOld = yMax;
// Update domains
var yMin = d3.min(data.map( function(d) { return d; } )),
yMax = d3.max(data.map( function(d) { return d; } )),
xMin = d3.min(data.map( function(d) { return d; } )),
xMax = d3.max(data.map( function(d) { return d; } ));
if(x.domain()[0] > newData[0] || x.domain()[1] < newData[0]) {
if(x.domain()[0] > newData[0]) {
x.domain([xMin, xMaxOld]);
} else {
x.domain([xMinOld, xMax]);
}
zoom.x(x);
}
if(y.domain()[0] > newData[0] || y.domain()[1] < newData[0]) {
if(y.domain()[0] > newData[0]) {
y.domain([yMin, yMaxOld]);
} else {
y.domain([yMinOld, yMax]);
}
zoom.y(y);
}
But eventually the view will still be reset because we pass the updated scales x and y into zoom...

nvd3.js-Line Chart with View Finder: rotate axis labels and show line values when mouse over

I'm new to this kind of forum and my English skills are not the best but I'll try to do my best :).
There is an example of a Line Chart with View Finder at nvd3 website. This is the one (examples\lineWithFocusChart.html, nvd3 zip package) which I have been working with during the last 2 days. I have made only one change to the example's format: I use dates in the X axis instead of normal numbers.
Here are my 2 questions:
1- How can i rotate all the ticks' labels in the x axis? My dates are too long (%x %X, day and time) and I want them rotated in oder to improve their viewing. I can only get 2 ticks rotated (the max and min, the edges, of the x axis). This is the code I modify inside the "switch (axis.orient())" block at nv.d3.js:
case 'bottom':
axisLabel.enter().append('text').attr('class', 'axislabel')
.attr('text-anchor', 'middle')
.attr('y', 25);
axisLabel
.attr('x', scale.range()[1] / 2);
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + scale(d) + ',0)'
})
.select('text')
.attr('dy', '.71em')
.attr('y', axis.tickPadding())
.attr('text-anchor', 'middle')
.text(function(d,i) {
return ('' + axis.tickFormat()(d)).match('NaN') ? '' : axis.tickFormat()(d)
})
.attr('transform', 'rotate(45)')
;
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(' + scale.range()[i] + ',0)'
});
}
break;
As you can check i have placed .attr('transform', 'rotate(45)') as new attribute so the max and min ticks are rotated (axisMaxMin). I have tried this way (throughout the nv.d3.js file) with the other text elements that I think are associated with the x ticks but it doesnt work. Any idea? Where I have to put the transformation in order to show all the X labels rotated?
2- In the example, when you place the mouse over the line, no event is triggered to show the value (x,y) associated with the point. How can i show those values? I've tried to copy-paste the methods used in other examples where these values are showed but it doesnt work. Any idea?
Thanks for sharing your time and knowledge :D.
There was a recent update to nvd3 that makes rotating the x-axis tick labels really easy. There is now a function of the axis model called rotateLabels(degrees) that takes an integer and will rotate your xTick labels the specified number of degrees. To rotate all xTick labels 45 degrees back, you could use it like this:
var chart = nv.models.lineChart();
chart.xAxis.rotateLabels(-45);

Categories

Resources