Ghost line path when zooming and panning a D3 chart - javascript

Learning D3 I created a chart based off this example. The chart is implemented as a JS closure, with Mike Bostock’s convention for creating reusable components in D3. (or as close as I can get)
When zooming and panning, the line path is not redrawn correctly.
In my chart I have a scatter plot and a line path joining the dots. The dots work but not the line. It's (maybe) something to do with rebinding the xScale during the onzoom behavior.... I've tried exposing the line function / object and a bunch of trial and error stuff but am at my wits end. Any help much appreciated.
Please see this codepen, or run the embedded code snippet.
http://codepen.io/Kickaha/pen/epzNyw
var MyNS = MyNS || {};
MyNS.EvalChartSeries = function () {
var xScale = d3.time.scale(),
yScale = d3.scale.linear();
//I tried exposing the line function / object to be able to call it in the on zoom ... no dice.
//var line = d3.svg.line();
var EvalChartSeries = function (selection) {
selection.each(function (dataIn) {
//select and bind data for scatter dots
spots = d3.select(this).selectAll("circle")
.data(dataIn);
//enter and create a circle for any unassigned datum
spots.enter().append("circle");
//update the bound items using the x-y scale function to recalculate
spots
.attr("r", 8)
.attr("cx", function (d) { return xScale(d.dt); })
.attr("cy", function (d) { return yScale(d.spot); })
.style("fill", function (d) {
switch (d.eva) {
case 1: return "green"; break;
case 2: return "red"; break;
case 3: return "blue"; break;
case 4: return "yellow"; break;}
});
//exit to remove any unused data, most likely not needed in this case as the data set is static
spots.exit().remove();
//here the line function/object is assigned it's scale and bound to data
var line = d3.svg.line().x(function (d) { return xScale(d.dt); })
.y(function (d) { return yScale(d.spot); }).interpolate("linear");
//and here is where the line is drawn by appending a set of svg path points
//, it does not use the select, enter, update, exit logic because a line while being a set of points is one thing (http://stackoverflow.com/questions/22508133/d3-line-chart-with-enter-update-exit-logic)
lines = d3.select(this)
.append("path");
lines
.attr('class', 'line')
.attr("d", line(dataIn))
.attr("stroke", "steelblue").attr("stroke-width", 1);
});
};
//The scales are exposed as properties, and they return the object to support chaining
EvalChartSeries.xScale = function (value) {
if (!arguments.length) {
return xScale;
}
xScale = value;
return EvalChartSeries;
};
EvalChartSeries.yScale = function (value) {
if (!arguments.length) {
return yScale;
}
yScale = value;
return EvalChartSeries;
};
/*
Here I tried to expose the line function/object as a property to rebind it to the xAxis when redrawing ... didnt work
EvalChartSeries.line = function (value) {
if (!arguments.length) {
return line;
}
line = value;
//linePath.x = function (d) { return xScale(d.dt); };
return EvalChartSeries;
};*/
//the function returns itself to suppport method chaining
return EvalChartSeries;
};
//The chart is defined here as a closure to enable Object Orientated reuse (encapsualtion / data hiding etc.. )
MyNS.DotsChart = (function () {
data = [{"dt":1280780384000,"spot":1.3173999786376953,"eva":4},
{"dt":1280782184000,"spot":1.3166999816894531,"eva":4},
{"dt":1280783084000,"spot":1.3164000511169434,"eva":4},
{"dt":1280781284000,"spot":1.3167999982833862,"eva":4},
{"dt":1280784884000,"spot":1.3162000179290771,"eva":4},
{"dt":1280783984000,"spot":1.3163000345230103,"eva":4},
{"dt":1280785784000,"spot":1.315999984741211,"eva":4},
{"dt":1280786684000,"spot":1.3163000345230103,"eva":4},
{"dt":1280787584000,"spot":1.316100001335144,"eva":4},
{"dt":1280788484000,"spot":1.3162000179290771,"eva":4},
{"dt":1280789384000,"spot":1.3164000511169434,"eva":4},
{"dt":1280790284000,"spot":1.3164000511169434,"eva":4},
{"dt":1280791184000,"spot":1.3166999816894531,"eva":4},
{"dt":1280792084000,"spot":1.3169000148773193,"eva":4},
{"dt":1280792984000,"spot":1.3170000314712524,"eva":4},
{"dt":1280793884000,"spot":1.3174999952316284,"eva":4},
{"dt":1280794784000,"spot":1.3171000480651855,"eva":4},
{"dt":1280795684000,"spot":1.3163000345230103,"eva":2},
{"dt":1280796584000,"spot":1.315600037574768,"eva":2},
{"dt":1280797484000,"spot":1.3154000043869019,"eva":2},
{"dt":1280798384000,"spot":1.3147000074386597,"eva":2},
{"dt":1280799284000,"spot":1.3164000511169434,"eva":2},
{"dt":1280800184000,"spot":1.3178000450134277,"eva":4},
{"dt":1280801084000,"spot":1.3176000118255615,"eva":4},
{"dt":1280801984000,"spot":1.3174999952316284,"eva":4},
{"dt":1280802884000,"spot":1.3193000555038452,"eva":3},
{"dt":1280803784000,"spot":1.32260000705719,"eva":4},
{"dt":1280804684000,"spot":1.3216999769210815,"eva":4},
{"dt":1280805584000,"spot":1.3233000040054321,"eva":4},
{"dt":1280806484000,"spot":1.3229000568389893,"eva":4},
{"dt":1280807384000,"spot":1.3229999542236328,"eva":2},
{"dt":1280808284000,"spot":1.3220000267028809,"eva":2},
{"dt":1280809184000,"spot":1.3224999904632568,"eva":2},
{"dt":1280810084000,"spot":1.3233000040054321,"eva":2},
{"dt":1280810984000,"spot":1.3240000009536743,"eva":2},
{"dt":1280811884000,"spot":1.3250000476837158,"eva":4},
{"dt":1280812784000,"spot":1.3253999948501587,"eva":4},
{"dt":1280813684000,"spot":1.3248000144958496,"eva":4},
{"dt":1280814584000,"spot":1.3250000476837158,"eva":4},
{"dt":1280815484000,"spot":1.3249000310897827,"eva":4},
{"dt":1280816384000,"spot":1.3238999843597412,"eva":2},
{"dt":1280817284000,"spot":1.3238999843597412,"eva":2},
{"dt":1280818184000,"spot":1.322700023651123,"eva":2},
{"dt":1280819084000,"spot":1.32260000705719,"eva":2},
{"dt":1280819984000,"spot":1.3219000101089478,"eva":2},
{"dt":1280820884000,"spot":1.323199987411499,"eva":4},
{"dt":1280821784000,"spot":1.3236000537872314,"eva":4},
{"dt":1280822684000,"spot":1.3228000402450562,"eva":4},
{"dt":1280823584000,"spot":1.3213000297546387,"eva":2},
{"dt":1280824484000,"spot":1.3214999437332153,"eva":2},
{"dt":1280825384000,"spot":1.3215999603271484,"eva":2},
{"dt":1280826284000,"spot":1.320199966430664,"eva":2},
{"dt":1280827184000,"spot":1.3187999725341797,"eva":2},
{"dt":1280828084000,"spot":1.3200000524520874,"eva":2},
{"dt":1280828984000,"spot":1.3207000494003296,"eva":1}
];
var minDate = d3.min(data, function (d) { return d.dt; }),
maxDate = d3.max(data, function (d) { return d.dt; });
var yMin = d3.min(data, function (d) { return d.spot; }),
yMax = d3.max(data, function (d) { return d.spot; });
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set up the drawing area
var margin = {top: 20, right: 20, bottom: 30, left: 35},
width = 1600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
//select the single element chart in the html body (this is expected to exist) and append a svg element
var plotChart =d3.select('#chart')
.append("svg:svg")
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('svg:g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var plotArea = plotChart.append('g')
.attr('clip-path', 'url(#plotAreaClip)');//http://stackoverflow.com/questions/940451/using-relative-url-in-css-file-what-location-is-it-relative-to
plotArea.append('clipPath')
.attr('id', 'plotAreaClip')
.append('rect')
.attr({ width: width, height: height });
// Scales
var xScale = d3.time.scale(),
yScale = d3.scale.linear();
// Set scale domains
xScale.domain([minDate, maxDate]);
yScale.domain([yMin, yMax]).nice();
// Set scale ranges
xScale.range([0, width]);
yScale.range([height, 0]);
// Axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(5);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
/* var line = d3.svg.line()
.x(function (d) { return xScale(d.dt); })
.y(function (d) { return yScale(d.spot); }).interpolate("linear");
*/
plotChart.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
plotChart.append('g')
.attr('class', 'y axis')
.call(yAxis);
// Data series
var series = MyNS.EvalChartSeries()
.xScale(xScale)
.yScale(yScale);
// .line(line); exposing this property did nothing
//appending a group 'g' tag binding the data and calling on our d3 line+dots chart object to process it
var dataSeries = plotArea.append('g')
.attr('class', 'series')
.datum(data)
.call(series);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Zooming and panning
//on zoom check extents , then most importantny redraw the chart
var zoom = d3.behavior.zoom()
.x(xScale)
.on('zoom', function() {
if (xScale.domain()[0] < minDate) {
zoom.translate([zoom.translate()[0] - xScale(minDate) + xScale.range()[0], 0]);
} else if (xScale.domain()[1] > maxDate) {
zoom.translate([zoom.translate()[0] - xScale(maxDate) + xScale.range()[1], 0]);
}
//most important to redraw "on zoom"
redrawChart();
});
//an overlay area to catch mouse events from the full area of the chart (not just the rendered dots and line)
var overlay = d3.svg.area()
.x(function (d) { return xScale(d.dt); })
.y0(0)
.y1(height);
//an area is a path object, not to be confused with our line path
plotArea.append('path')
.attr('class', 'overlay')
.attr('d', overlay(data))
.call(zoom);
redrawChart();
updateZoomFromChart();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
function redrawChart() {
//redraws the scatter data series
dataSeries.call(series);
//redraws the xaxis to show the current zoom pan area
plotChart.select('.x.axis').call(xAxis);
// plotChart.select(".line")
// .attr("class", "line");
// .attr("d", line);
//filters the data set to what is visible given teh current zoom pan state
var yExtent = d3.extent(data.filter(function (d) {
var dt = xScale(d.dt);
return dt > 0 && dt < width;
}), function (d) { return d.spot; });
yScale.domain(yExtent).nice();
//this scales the y axis to maximum visibility as the line is zoomed and panned
plotChart.select(".y.axis").call(yAxis);
}
//takes care of zooming and panning past the ends of the data.
function updateZoomFromChart() {
var fullXDomain = maxDate - minDate,
currentXDomain = xScale.domain()[1] - xScale.domain()[0];
var minXScale = currentXDomain / fullXDomain,
maxXScale = minXScale * 20;
zoom.x(xScale)
.scaleExtent([minXScale, maxXScale]);
}})()
#chart {
margin-top: 20px;
margin-bottom: 20px;
width: 660px;
}.chart .overlay {
stroke-width: 0px;
fill-opacity: 0;
}
.overlay {
stroke-width: 0px;
fill-opacity: 0;
}
body {
padding: 10px 20px;
background: #ffeeee;
font-family: sans-serif;
text-align: center;
color: #7f7;
}.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart"></div>
How do I get the line to redraw correctly?

Thank you for a very well documented question.
What you are doing, is that on zoom you re-draw the line, without removing the one already existing in your SVG element. May I suggest the following:
Change your zoom method to:
var zoom = d3.behavior.zoom()
.x(xScale)
.on('zoom', function() {
if (xScale.domain()[0] < minDate) {
zoom.translate([zoom.translate()[0] - xScale(minDate) + xScale.range()[0], 0]);
} else if (xScale.domain()[1] > maxDate) {
zoom.translate([zoom.translate()[0] - xScale(maxDate) + xScale.range()[1], 0]);
}
// add the following line, to remove the lines already present
d3.selectAll('.line').remove()
//most important to redraw "on zoom"
redrawChart();
});
I am sure there are better ways of doing it, but I think this will get you started.
Hope it helps.

Related

D3: slow zoomable heatmap

I have this zoomable heatmap, which looks too slow when zooming-in or out. Is there anything to make it faster/smoother or it is just too many points and that is the best I can have. I was wondering if there is some trick to make it lighter for the browser please while keeping enhancements like tooltips. Or maybe my code handling the zoom feature is not great .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000000;
}
.x.axis path {
//display: none;
}
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
#tooltip {
position:absolute;
background-color: #2B292E;
color: white;
font-family: sans-serif;
font-size: 15px;
pointer-events: none; /*dont trigger events on the tooltip*/
padding: 15px 20px 10px 20px;
text-align: center;
opacity: 0;
border-radius: 4px;
}
</style>
<title>Bar Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
</head>
<body>
<div id="chart" style="width: 700px; height: 500px"></div>
<script>
var dataset = [];
for (let i = 1; i < 360; i++) {
for (j = 1; j < 75; j++) {
dataset.push({
day: i,
hour: j,
tOutC: Math.random() * 25,
})
}
};
var days = d3.max(dataset, function(d) {
return d.day;
}) -
d3.min(dataset, function(d) {
return d.day;
});
var hours = d3.max(dataset, function(d) {
return d.hour;
}) -
d3.min(dataset, function(d) {
return d.hour;
});
var tMin = d3.min(dataset, function(d) {
return d.tOutC;
}),
tMax = d3.max(dataset, function(d) {
return d.tOutC;
});
var dotWidth = 1,
dotHeight = 3,
dotSpacing = 0.5;
var margin = {
top: 0,
right: 25,
bottom: 40,
left: 25
},
width = (dotWidth * 2 + dotSpacing) * days,
height = (dotHeight * 2 + dotSpacing) * hours;
var colors = ['#2C7BB6', '#00A6CA','#00CCBC','#90EB9D','#FFFF8C','#F9D057','#F29E2E','#E76818','#D7191C'];
var xScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.day}))
.range([0, width]);
var yScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.hour}))
.range([(dotHeight * 2 + dotSpacing) * hours, dotHeight * 2 + dotSpacing]);
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function(d) {
return d.tOutC;
})])
.range(colors);
var xAxis = d3.axisBottom().scale(xScale);
// Define Y axis
var yAxis = d3.axisLeft().scale(yScale);
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.translateExtent([
[80, 20],
[width, height]
])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Clip path
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// Heatmap dots
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll("ellipse")
.data(dataset)
.enter()
.append("ellipse")
.attr("cx", function(d) {
return xScale(d.day);
})
.attr("cy", function(d) {
return yScale(d.hour);
})
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function(d) {
return colorScale(d.tOutC);
})
.on("mouseover", function(d){
$("#tooltip").html("X: "+d.day+"<br/>Y:"+d.hour+"<br/>Value:"+Math.round(d.tOutC*100)/100);
var xpos = d3.event.pageX +10;
var ypos = d3.event.pageY +20;
$("#tooltip").css("left",xpos+"px").css("top",ypos+"px").animate().css("opacity",1);
}).on("mouseout", function(){
$("#tooltip").animate({duration: 500}).css("opacity",0);
});
//Create X axis
var renderXAxis = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + yScale(0) + ")")
.call(xAxis)
//Create Y axis
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
// update: rescale x axis
renderXAxis.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
update();
}
function update() {
// update: cache rescaleX value
var rescaleX = d3.event.transform.rescaleX(xScale);
svg.selectAll("ellipse")
.attr('clip-path', 'url(#clip)')
// update: apply rescaleX value
.attr("cx", function(d) {
return rescaleX(d.day);
})
// .attr("cy", function(d) {
// return yScale(d.hour);
// })
// update: apply rescaleX value
.attr("rx", function(d) {
return (dotWidth * d3.event.transform.k);
})
.attr("fill", function(d) {
return colorScale(d.tOutC);
});
}
</script>
</body>
</html>
Thanks
The solution is not to update all the dots for the zoom but to apply the zoom transform to the group containing the dots.
Clipping of the group needs to be done on an additional parent g heatDotsGroup.
The zoom scale of y is taken care of (set it fixed to 1) with a regex replace, limit translate in y by setting the transform.y to 0, and limit the translate of x based on the current scale.
Allow a little translate past 0 to show the first dot complete when zoomed in.
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.on("zoom", zoomed);
// Heatmap dots
var heatDotsGroup = svg.append("g")
.attr("clip-path", "url(#clip)")
.append("g");
heatDotsGroup.selectAll("ellipse")
.data(dataset)
.enter()
.append("ellipse")
.attr("cx", function(d) { return xScale(d.day); })
.attr("cy", function(d) { return yScale(d.hour); })
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function(d) { return colorScale(d.tOutC); })
.on("mouseover", function(d){
$("#tooltip").html("X: "+d.day+"<br/>Y:"+d.hour+"<br/>Value:"+Math.round(d.tOutC*100)/100);
var xpos = d3.event.pageX +10;
var ypos = d3.event.pageY +20;
$("#tooltip").css("left",xpos+"px").css("top",ypos+"px").animate().css("opacity",1);
}).on("mouseout", function(){
$("#tooltip").animate({duration: 500}).css("opacity",0);
});
function zoomed() {
d3.event.transform.y = 0;
d3.event.transform.x = Math.min(d3.event.transform.x, 5);
d3.event.transform.x = Math.max(d3.event.transform.x, (1-d3.event.transform.k) * width );
// update: rescale x axis
renderXAxis.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
heatDotsGroup.attr("transform", d3.event.transform.toString().replace(/scale\((.*?)\)/, "scale($1, 1)"));
}
Try Canvas
You have 27 000 nodes. This is probably around the point where SVG performance drops off for most and Canvas starts to really shine. Sure, Canvas isn't stateful like SVG, its just pixels with no nice elements to mouse over in the DOM and tell you where and what they are. But, there are ways to address this shortcoming so that we can retain speed and interactive abilities.
For the initial rendering using your snippet, I have a average rendering time of ~440ms. But, through the magic of canvas, I can render the same heat map with an average rendering time of ~103ms. Those savings can be applied to things like zooming, animation etc.
For very small things like your ellipses there is a risk of aliasing issues that is harder to fix with canvas as opposed to SVG, though how each browser renders this will differ
Design Implications
With Canvas we can retain the enter/exit/update cycle as with SVG, but we also have the option of dropping it. At times the enter/exit/update cycle pairs extremely well with canvas: transitions, dynamic data, heirarcical data, etc. I have previously spent some time on some of the higher level differences between Canvas and SVG with regards to D3 here.
For my answer here, we'll leave the enter cycle. When we want to update the visualization we just redraw everything based on the data array itself.
Drawing the Heat Map
I'm using rectangles for the sake of brevity. Canvas's ellipse method isn't quite ready, but you can emulate it easily enough.
We need a function that draws the dataset. If you had x/y/color hard coded into the dataset we could use a very simple:
function drawNodes()
dataset.forEach(function(d) {
ctx.beginPath();
ctx.rect(d.x,d.y,width,height);
ctx.fillStyle = d.color;
ctx.fill();
})
}
But we need to scale your values, calculate a color, and we should apply the zoom. I ended up with a relatively simple:
function drawNodes()
var k = d3.event ? d3.event.transform.k : 1;
var dw = dotWidth * k;
ctx.clearRect(0,0,width,height); // erase what's there
dataset.forEach(function(d) {
var x = xScale(d.day);
var y = yScale(d.hour);
var fill = colorScale(d.tOutC);
ctx.beginPath();
ctx.rect(x,y,dw,dotHeight);
ctx.fillStyle = fill;
ctx.strokeStyle = fill;
ctx.stroke();
ctx.fill();
})
}
This can be used to initially draw the nodes (when d3.event isn't defined), or on zoom/pan events (after which this function is called each time).
What about the axes?
d3-axis is intended for SVG. So, I've just superimposed an SVG overtop of a Canvas element positioning both absolutely and disabling mouse events on the overlying SVG.
Speaking of axes, I only have one drawing function (no difference between update/initial drawing), so I use a reference x scale and a rendering x scale from the get go, rather than creating a disposable rescaled x scale in the update function
Now I Have a Canvas, How Do I Interact With It?
There are a few methods we could use take a pixel position and convert it to a specific datum:
Use a Voronoi diagram (using the .find method to locate a datum)
Use a Force layout (also using the .find method to locate a datum)
Use a hidden Canvas (using pixel color to indicate datum index)
Use a scale's invert function (when data is gridded)
The third option may be one of the most common, and while the first two look similar the find methods do differ internally (voronoi neighbors vs quad tree). The last method is fairly appropriate in this case: we have a grid of data and we can invert the mouse coordinate to get row and column data. Based on your snippet that might look like:
function mousemove() {
var xy = d3.mouse(this);
var x = Math.round(xScale.invert(xy[0]));
var y = Math.round(yScale.invert(xy[1]));
// For rounding on canvas edges:
if(x > xScaleRef.domain()[1]) x = xScaleRef.domain()[1];
if(x < xScaleRef.domain()[0]) x = xScaleRef.domain()[0];
if(y > yScale.domain()[1]) y = yScale.domain()[1];
if(y < yScale.domain()[0]) y = yScale.domain()[0];
var index = --x*74 + y-1; // minus ones for non zero indexed x,y values.
var d = dataset[index];
console.log(x,y,index,d)
$("#tooltip").html("X: "+d.day+"<br/>Y:"+d.hour+"<br/>Value:"+Math.round(d.tOutC*100)/100);
var xpos = d3.event.pageX +10;
var ypos = d3.event.pageY +20;
$("#tooltip").css("left",xpos+"px").css("top",ypos+"px").animate().css("opacity",1);
}
*I've used mousemove since mouseover will trigger once when moving over the canvas, we need to continuously update, if we wanted to hide the tooltip, we could just check to see if the pixel selected is white:
var p = ctx.getImageData(xy[0], xy[1], 1, 1).data; // pixel data:
if (!p[0] && !p[1] && !p[2]) { /* show tooltip */ }
else { /* hide tooltip */ }
Example
I've explicitly mentioned most of the changes above, but I've made some additional changes below. First, I need to select the canvas, position it, get the context, etc. I also have swapped rects for ellipses, so the positioning is a bit different (but you have other positioning issues to from using a linear scale (the ellipse centroids can fall on the edge of the svg as is), I've not modified this to account for the width/height of the ellipses/rects. This scale issue was far enough from the question that I didn't modify it.
var dataset = [];
for (let i = 1; i < 360; i++) {
for (j = 1; j < 75; j++) {
dataset.push({
day: i,
hour: j,
tOutC: Math.random() * 25,
})
}
};
var days = d3.max(dataset, function(d) { return d.day; }) - d3.min(dataset, function(d) { return d.day; });
var hours = d3.max(dataset, function(d) { return d.hour; }) - d3.min(dataset, function(d) { return d.hour; });
var tMin = d3.min(dataset, function(d) { return d.tOutC; }), tMax = d3.max(dataset, function(d) { return d.tOutC; });
var dotWidth = 1,
dotHeight = 3,
dotSpacing = 0.5;
var margin = { top: 20, right: 25, bottom: 40, left: 25 },
width = (dotWidth * 2 + dotSpacing) * days,
height = (dotHeight * 2 + dotSpacing) * hours;
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
var colors = ['#2C7BB6', '#00A6CA','#00CCBC','#90EB9D','#FFFF8C','#F9D057','#F29E2E','#E76818','#D7191C'];
var xScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.day}))
.range([0, width]);
var xScaleRef = xScale.copy();
var yScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.hour}))
.range([height,0]);
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function(d) { return d.tOutC; })])
.range(colors);
var xAxis = d3.axisBottom().scale(xScale);
var yAxis = d3.axisLeft().scale(yScale);
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.translateExtent([
[0,0],
[width, height]
])
.on("zoom", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG & Canvas:
var canvas = d3.select("#chart")
.append("canvas")
.attr("width", width)
.attr("height", height)
.style("left", margin.left + "px")
.style("top", margin.top + "px")
.style("position","absolute")
.on("mousemove", mousemove)
.on("mouseout", mouseout);
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform","translate("+[margin.left,margin.top]+")");
var ctx = canvas.node().getContext("2d");
canvas.call(zoom);
// Initial Draw:
drawNodes(dataset);
//Create Axes:
var renderXAxis = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + yScale(0) + ")")
.call(xAxis)
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// Handle Zoom:
function zoomed() {
// rescale the x Axis:
xScale = d3.event.transform.rescaleX(xScaleRef); // Use Reference Scale.
// Redraw the x Axis:
renderXAxis.call(xAxis.scale(xScale));
// Clear and redraw the nodes:
drawNodes();
}
// Draw nodes:
function drawNodes() {
var k = d3.event ? d3.event.transform.k : 1;
var dw = dotWidth * k;
ctx.clearRect(0,0,width,height);
dataset.forEach(function(d) {
var x = xScale(d.day);
var y = yScale(d.hour);
var fill = colorScale(d.tOutC);
ctx.beginPath();
ctx.rect(x,y,dw,dotHeight);
ctx.fillStyle = fill;
ctx.strokeStyle = fill;
ctx.stroke();
ctx.fill();
})
}
// Mouse movement:
function mousemove() {
var xy = d3.mouse(this);
var x = Math.round(xScale.invert(xy[0]));
var y = Math.round(yScale.invert(xy[1]));
if(x > xScaleRef.domain()[1]) x = xScaleRef.domain()[1];
if(x < xScaleRef.domain()[0]) x = xScaleRef.domain()[0];
if(y > yScale.domain()[1]) y = yScale.domain()[1];
if(y < yScale.domain()[0]) y = yScale.domain()[0];
var index = --x*74 + y-1; // minus ones for non zero indexed x,y values.
var d = dataset[index];
$("#tooltip").html("X: "+d.day+"<br/>Y:"+d.hour+"<br/>Value:"+Math.round(d.tOutC*100)/100);
var xpos = d3.event.pageX +10;
var ypos = d3.event.pageY +20;
$("#tooltip").css("left",xpos+"px").css("top",ypos+"px").animate().css("opacity",1);
}
function mouseout() {
$("#tooltip").animate({duration: 500}).css("opacity",0);
};
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000000;
}
.x.axis path {
//display: none;
}
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
#tooltip {
position:absolute;
background-color: #2B292E;
color: white;
font-family: sans-serif;
font-size: 15px;
pointer-events: none; /*dont trigger events on the tooltip*/
padding: 15px 20px 10px 20px;
text-align: center;
opacity: 0;
border-radius: 4px;
}
svg {
position: absolute;
top: 0;
left:0;
pointer-events: none;
}
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<div id="chart" style="width: 700px; height: 500px"></div>
The result of all following combined suggestions is not perfect, but it is subjectively slightly better:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000000;
}
.x.axis path {
//display: none;
}
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
#tooltip {
position:absolute;
background-color: #2B292E;
color: white;
font-family: sans-serif;
font-size: 15px;
pointer-events: none; /*dont trigger events on the tooltip*/
padding: 15px 20px 10px 20px;
text-align: center;
opacity: 0;
border-radius: 4px;
}
</style>
<title>Bar Chart</title>
<!-- Reference style.css -->
<!-- <link rel="stylesheet" type="text/css" href="style.css">-->
<!-- Reference minified version of D3 -->
<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
</head>
<body>
<div id="chart" style="width: 700px; height: 500px"></div>
<script>
var dataset = [];
for (let i = 1; i < 360; i++) {
for (j = 1; j < 75; j++) {
dataset.push({
day: i,
hour: j,
tOutC: Math.random() * 25,
})
}
};
var days = d3.max(dataset, function(d) {
return d.day;
}) -
d3.min(dataset, function(d) {
return d.day;
});
var hours = d3.max(dataset, function(d) {
return d.hour;
}) -
d3.min(dataset, function(d) {
return d.hour;
});
var tMin = d3.min(dataset, function(d) {
return d.tOutC;
}),
tMax = d3.max(dataset, function(d) {
return d.tOutC;
});
var dotWidth = 1,
dotHeight = 3,
dotSpacing = 0.5;
var margin = {
top: 0,
right: 25,
bottom: 40,
left: 25
},
width = (dotWidth * 2 + dotSpacing) * days,
height = (dotHeight * 2 + dotSpacing) * hours;
var colors = ['#2C7BB6', '#00A6CA','#00CCBC','#90EB9D','#FFFF8C','#F9D057','#F29E2E','#E76818','#D7191C'];
var xScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.day}))
.range([0, width]);
var yScale = d3.scaleLinear()
.domain(d3.extent(dataset, function(d){return d.hour}))
.range([(dotHeight * 2 + dotSpacing) * hours, dotHeight * 2 + dotSpacing]);
var colorScale = d3.scaleQuantile()
.domain([0, colors.length - 1, d3.max(dataset, function(d) {
return d.tOutC;
})])
.range(colors);
var xAxis = d3.axisBottom().scale(xScale);
// Define Y axis
var yAxis = d3.axisLeft().scale(yScale);
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.translateExtent([
[80, 20],
[width, height]
])
// .on("zoom", zoomed);
.on("end", zoomed);
var tooltip = d3.select("body").append("div")
.attr("id", "tooltip")
.style("opacity", 0);
// SVG canvas
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Clip path
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// Heatmap dots
svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll("ellipse")
.data(dataset)
.enter()
.append("ellipse")
.attr("cx", function(d) {
return xScale(d.day);
})
.attr("cy", function(d) {
return yScale(d.hour);
})
.attr("rx", dotWidth)
.attr("ry", dotHeight)
.attr("fill", function(d) {
return colorScale(d.tOutC);
})
.on("mouseover", function(d){
$("#tooltip").html("X: "+d.day+"<br/>Y:"+d.hour+"<br/>Value:"+Math.round(d.tOutC*100)/100);
var xpos = d3.event.pageX +10;
var ypos = d3.event.pageY +20;
$("#tooltip").css("left",xpos+"px").css("top",ypos+"px").animate().css("opacity",1);
}).on("mouseout", function(){
$("#tooltip").animate({duration: 500}).css("opacity",0);
});
//Create X axis
var renderXAxis = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + yScale(0) + ")")
.call(xAxis)
//Create Y axis
var renderYAxis = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
// update: rescale x axis
renderXAxis.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
update();
}
function update() {
// update: cache rescaleX value
var rescaleX = d3.event.transform.rescaleX(xScale);
var scaledRadius = dotWidth * d3.event.transform.k;
var scaledCxes = [...Array(360).keys()].map(i => rescaleX(i));
svg.selectAll("ellipse")
// .attr('clip-path', 'url(#clip)')
// update: apply rescaleX value
.attr("cx", d => scaledCxes[d.day])
// .attr("cy", function(d) {
// return yScale(d.hour);
// })
// update: apply rescaleX value
.attr("rx", scaledRadius)
// .attr("fill", function(d) {
// return colorScale(d.tOutC);
// });
}
</script>
</body>
</html>
Using on("end", zoomed) instead of on("zoom", zoomed):
First thing we can try is to activate the zoom change only at the end of the zoom event in order not to have these non deterministic updates jumps during a single zoom event. It has for effect to lower the required processing as only one computation happens, and it removes the global jump discomfort:
var zoom = d3.zoom()
.scaleExtent([dotWidth, dotHeight])
.translateExtent([ [80, 20], [width, height] ])
.on("end", zoomed); // instead of .on("zoom", zoomed);
Remove updates of things which remains the same during the zoom:
We can also remove from the nodes update things which stay the same such as the color of a circle which during the zoom remains the same anyway .attr("fill", function(d) { return colorScale(d.tOutC); }); and .attr('clip-path', 'url(#clip)').
Computing only once things used several times:
The new circle radius after the zoom can only be computed once instead of 27K times as it's the same for all circles:
var scaledRadius = dotWidth * d3.event.transform.k;
.attr("rx", scaledRadius)
Same for x positions, we can compute it once per possible x value (360 times) and store it in an array to access them in constant time instead of computing it 27K times:
var scaledCxes = [...Array(360).keys()].map(i => rescaleX(i));
.attr("cx", d => scaledCxes[d.day])
Last obvious option would be to reduce the number of nodes since it's the root of the issue!
If the zoom extent would have been bigger, I would have also suggested filtering nodes not visible anymore.
Do check LightningChart JS heatmaps - it's free to use non-commercially.
Here is a performance comparison of best performing heatmap web charts https://github.com/Arction/javascript-charts-performance-comparison-heatmaps
As you can see over there we are talking about visualizing heatmaps that are in range of billions of data points and user interactions still work just fine.
// Source https://www.arction.com/lightningchart-js-interactive-examples/edit/lcjs-example-0800-heatmapGrid.html
/*
* LightningChartJS example that showcases a simple XY line series.
*/
// Extract required parts from LightningChartJS.
const { lightningChart, PalettedFill, LUT, ColorRGBA, emptyLine, Themes } =
lcjs;
const { createWaterDropDataGenerator } = xydata;
// Specify the resolution used for the heatmap.
const resolutionX = 1000;
const resolutionY = 1000;
// Create a XY Chart.
const chart = lightningChart()
.ChartXY({
// theme: Themes.darkGold
})
.setTitle(
`Heatmap Grid Series ${resolutionX}x${resolutionY} (${(
(resolutionX * resolutionY) /
1000000
).toFixed(1)} million data points)`
)
.setPadding({ right: 40 });
// Create LUT and FillStyle
const palette = new LUT({
units: "intensity",
steps: [
{ value: 0, color: ColorRGBA(255, 255, 0) },
{ value: 30, color: ColorRGBA(255, 204, 0) },
{ value: 45, color: ColorRGBA(255, 128, 0) },
{ value: 60, color: ColorRGBA(255, 0, 0) },
],
interpolate: false,
});
// Generate heatmap data.
createWaterDropDataGenerator()
.setRows(resolutionX)
.setColumns(resolutionY)
.generate()
.then((data) => {
// Add a Heatmap to the Chart.
const heatmap = chart
.addHeatmapGridSeries({
columns: resolutionX,
rows: resolutionY,
start: { x: 0, y: 0 },
end: { x: resolutionX, y: resolutionY },
dataOrder: "columns",
})
// Color Heatmap using previously created color look up table.
.setFillStyle(new PalettedFill({ lut: palette }))
.setWireframeStyle(emptyLine)
.invalidateIntensityValues(data)
.setMouseInteractions(false);
// Add LegendBox.
const legend = chart.addLegendBox()
// Dispose example UI elements automatically if they take too much space. This is to avoid bad UI on mobile / etc. devices.
.setAutoDispose({
type: 'max-height',
maxHeight: 0.70,
})
.add(chart)
});
<script src="http://unpkg.com/#arction/lcjs#3.1.0/dist/lcjs.iife.js"></script>
<script src="http://unpkg.com/#arction/xydata#1.4.0/dist/xydata.iife.js"></script>

Adding color dynamically to a multiple line chart but it is not working in d3.js

I have created this curve line chart and I filled by purple color only. Then I decided to add color range and I used color scaling method is Category10 but it is not working. I am new to D3.js and it has been my headache for the past week.
In order to make it look more presentable, I need to add colors and I did tried to add this way by using .style attribute but
function buildLine(data){
var xScale=d3.scale.linear()
.domain([0,d3.max(data,function(d){return d.spend;})])
.range([0, w]);
var yScale=d3.scale.linear()
.domain([0,d3.max(data,function(d){return d.alpha;})])
.range([h/2, 0]);
var yAxisGen=d3.svg.axis().scale(yScale).orient("left");
var xAxisGen=d3.svg.axis().scale(xScale).orient("bottom");
var svg=d3.select("body").append("svg").attr({width:w,height:h});
var yAxis= svg.append("g")
.call(yAxisGen)
.attr("class","axis")
.attr("transform", "translate(50, " +10 +")");
var xAxisTranslate = h/2 + 10;
var xAxis= svg.append("g")
.call(xAxisGen)
.attr("class","axis")
.attr("transform", "translate(50, " + xAxisTranslate +")");
Adding color function here
var color=d3.scale.category10
var lineFun = d3.svg.line()
.x(function (d) { return xScale(d.x); })
.y(function (d) { return yScale(d.y); })
.interpolate("basis");
Here I tried to add it dynamically. '.style does not work. WHy?'
var viz = svg.selectAll("path")
.data(data)
.enter()
.append("path")
.attr({
d: function(d) {
return lineFun(d.arr)
},
"stroke": "purple",
"stroke-width": 2,
"fill": "none",
"class":"line"
})
.style("stroke",function(){
return d.color=color(d.arr);
})
.attr("transform", "translate(48, " + 10 +")")
;
}
d3.json("sample-data.json",function(error,data){
//check the file loaded properly
if (error) { //is there an error?
console.log(error); //if so, log it to the console
} else { //If not we're golden!
//Now show me the money!
ds=data; //put the data in the global var
}
data.forEach(function(jsonData){
var lineData = d3.range(0, jsonData.spend, 100)
.map(x => [x, (jsonData.alpha * (1 - Math.pow(2.71828, (-jsonData.beta * x))))] );
/* console.log("this is the data:",lineData);*/
//i think line date returns an array with each item in it also an array of 2 items
var arr = [];
for (var i = 0; i < lineData.length; i++) {
arr.push({
x: lineData[i][0],
y: lineData[i][1]
});
}
jsonData.arr = arr;
console.log(jsonData);
});
buildLine(data);
});
These are the problems:
You have to call the scale function:
var color=d3.scale.category10()
//parentheses here ----------^
You cannot use the argument d if you don't set the anonymous function parameter:
.style("stroke",function(d){
//parameter here-----^
return d.color=color(d.arr);
})
scale.category10() works on a "first come, first served" basis. You just need the index:
.style("stroke",function(d,i){
return d.color=color(i);
});
Here is a demo showing how to use that scale:
var color = d3.scale.category10();
var divs = d3.select("body").selectAll(null)
.data(d3.range(10))
.enter()
.append("div")
.style("background-color", function(d, i) {
return color(i)
})
div {
width: 20px;
height: 20px;
display: inline-block;
margin: 2px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

Why is that d3.js pie chart transition not working?

Today I'm working with d3.js on a simple pie chart.
I used the tutorials here to build my first pie chart, yet I wanted to customize it a bit, so my code won't exactly looked like the same.
My problem occured while working on Step 6, to add some interactivity to my chart.
As shown here the pie chart should allow me to click on its legend to toggle some data. Yet, if the hover tool is working with my code (toggling effectively changes the values inside the hover box), the chart itself doesn't change.
When toggling, my browser console throws that error :
d3.v3.js:5737 Uncaught TypeError: Cannot use 'in' operator to search for 'data' in undefined
After some testing, I realised the error occured because of that part of the javascript :
var path = g.data(pie(data));
path.transition()
.duration(750)
.attrTween('d', function(d) {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
which is the same as in the demo. So, the rest of my code might occasion that error, yet I don't know what could 'cause it.
Here is what I've done so far :
Styling :
#chart {
height: 360px;
margin: 0 auto;
position: relative;
width: 360px;
}
.tool {
background: #eee;
box-shadow: 0 0 5px #999999;
color: #333;
display: none;
font-size: 12px;
left: 130px;
padding: 10px;
position: absolute;
text-align: center;
top: 95px;
width: 80px;
z-index: 10;
}
/* replace bootstrap css */
.label {
color: #000000
}
/* css for the legend*/
.legend {
font-size: 12px;
}
rect {
cursor: pointer;
stroke-width: 2;
}
rect.disabled {
fill: transparent !important;
}
Script :
// var definition
var legendRectSize = 18;
var legendSpacing = 4;
// defines chart boundaries
var width = 960;
var height = 500;
var radius = Math.min(width, height) / 2;
var DonutWidth = 80;
// defines a charter of colors for the chart
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
// defines graphical attributes for the chart
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - DonutWidth);
var labelArc = d3.svg.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.TST; });
// add the chart to the html doc
var svg = d3.select('#chart').append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// add objects needed for the hover tool
var tool = d3.select('#chart')
.append('div')
.attr('class', 'tool');
tool.append('div')
.attr('class', 'label');
tool.append('div')
.attr('class', 'count');
tool.append('div')
.attr('class', 'percent');
// loads data
d3.json("/media/Storage/bar_chart.json", function(data) {
// creates a variable to know if a column will be displayed or not
data.forEach(function(d) {
d.TST = +d.TST;
d.enabled = true;
});
// creates the pie chart from data
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.attr("fill", function(d, i) { return color(d.data.OPCODE); })
.each(function(d){this._current = d;});
// displays data on hover
g.on('mouseover',function(d){
var total = d3.sum(data.map(function(d) {
return (d.enabled) ? d.TST : 0;
}));
var percent = Math.round(1000 * d.data.TST / total) / 10;
tool.select('.label').html(d.data.OPCODE);
tool.select('.count').html(d.data.TST);
tool.select('.percent').html(percent + '%');
tool.style('display', 'block');
});
// toggles off hoverbox
g.on('mouseout', function(d){
tool.style('display', 'none');
});
// add the legend to the chart
var legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = height * color.domain().length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color)
// function which toggles data to exclude of display
.on('click', function(OPCODE){
var rect = d3.select(this);
var enabled = true;
var totalEnabled = d3.sum(data.map(function(d) {
return (d.enabled) ? 1 : 0;
}));
if (rect.attr('class') === 'disabled') {
rect.attr('class', '');
} else {
if (totalEnabled < 2) return;
rect.attr('class', 'disabled');
enabled = false;
}
// defines a new way to retrieve data for the chart, selecting only enabled data
pie.value(function(d) {
if (d.OPCODE === OPCODE) d.enabled = enabled;
return (d.enabled) ? d.TST : 0;
});
//incriminated part of the script
var path = g.data(pie(data));
// animation for the chart
path.transition()
.duration(750)
.attrTween('d', function(d) {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
});
});
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; });
});
Thanks a lot for your help.
EDIT :
Link to a JSFiddle
Since I'm using a json file I'm loading locally in my app, here I had to use a local variable where my JSON was put, yet it is clearly inefficient and brought other bugs...
You have this._current undefined at this line var i = d3.interpolate(this._current, d); fix it and the rest is good enough. Instead of this.current try with some temp var which is accessible in any place in the code .And you would only see transition if the new data is different from the old data try with two sets of json and onClick pass the new json data.

d3js Load chart data from external csv file

I'm Trying to implement the simple chart similar to the example as in below link from d3js
http://bl.ocks.org/NPashaP/96447623ef4d342ee09b
Goal is to implement this example from .csv file as for my requirement data changes dynamically.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body{
width:1060px;
margin:50px auto;
}
path { stroke: #fff; }
path:hover { opacity:0.9; }
rect:hover { fill:blue; }
.axis { font: 10px sans-serif; }
.legend tr{ border-bottom:1px solid grey; }
.legend tr:first-child{ border-top:1px solid grey; }
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path { display: none; }
.legend{
margin-bottom:76px;
display:inline-block;
border-collapse: collapse;
border-spacing: 0px;
}
.legend td{
padding:4px 5px;
vertical-align:bottom;
}
.legendFreq, .legendPerc{
align:right;
width:50px;
}
</style>
<body>
<div id='dashboard'>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
function dashboard(id, fData){
var barColor = 'steelblue';
function segColor(c){ return {low:"#807dba", mid:"#e08214",high:"#41ab5d"}[c]; }
// compute total for each state.
fData.forEach(function(d){d.total=d.freq.low+d.freq.mid+d.freq.high;});
// function to handle histogram.
function histoGram(fD){
var hG={}, hGDim = {t: 60, r: 0, b: 30, l: 0};
hGDim.w = 500 - hGDim.l - hGDim.r,
hGDim.h = 300 - hGDim.t - hGDim.b;
//create svg for histogram.
var hGsvg = d3.select(id).append("svg")
.attr("width", hGDim.w + hGDim.l + hGDim.r)
.attr("height", hGDim.h + hGDim.t + hGDim.b).append("g")
.attr("transform", "translate(" + hGDim.l + "," + hGDim.t + ")");
// create function for x-axis mapping.
var x = d3.scale.ordinal().rangeRoundBands([0, hGDim.w], 0.1)
.domain(fD.map(function(d) { return d[0]; }));
// Add x-axis to the histogram svg.
hGsvg.append("g").attr("class", "x axis")
.attr("transform", "translate(0," + hGDim.h + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Create function for y-axis map.
var y = d3.scale.linear().range([hGDim.h, 0])
.domain([0, d3.max(fD, function(d) { return d[1]; })]);
// Create bars for histogram to contain rectangles and freq labels.
var bars = hGsvg.selectAll(".bar").data(fD).enter()
.append("g").attr("class", "bar");
//create the rectangles.
bars.append("rect")
.attr("x", function(d) { return x(d[0]); })
.attr("y", function(d) { return y(d[1]); })
.attr("width", x.rangeBand())
.attr("height", function(d) { return hGDim.h - y(d[1]); })
.attr('fill',barColor)
.on("mouseover",mouseover)// mouseover is defined below.
.on("mouseout",mouseout);// mouseout is defined below.
//Create the frequency labels above the rectangles.
bars.append("text").text(function(d){ return d3.format(",")(d[1])})
.attr("x", function(d) { return x(d[0])+x.rangeBand()/2; })
.attr("y", function(d) { return y(d[1])-5; })
.attr("text-anchor", "middle");
function mouseover(d){ // utility function to be called on mouseover.
// filter for selected state.
var st = fData.filter(function(s){ return s.State == d[0];})[0],
nD = d3.keys(st.freq).map(function(s){ return {type:s, freq:st.freq[s]};});
// call update functions of pie-chart and legend.
pC.update(nD);
leg.update(nD);
}
function mouseout(d){ // utility function to be called on mouseout.
// reset the pie-chart and legend.
pC.update(tF);
leg.update(tF);
}
// create function to update the bars. This will be used by pie-chart.
hG.update = function(nD, color){
// update the domain of the y-axis map to reflect change in frequencies.
y.domain([0, d3.max(nD, function(d) { return d[1]; })]);
// Attach the new data to the bars.
var bars = hGsvg.selectAll(".bar").data(nD);
// transition the height and color of rectangles.
bars.select("rect").transition().duration(500)
.attr("y", function(d) {return y(d[1]); })
.attr("height", function(d) { return hGDim.h - y(d[1]); })
.attr("fill", color);
// transition the frequency labels location and change value.
bars.select("text").transition().duration(500)
.text(function(d){ return d3.format(",")(d[1])})
.attr("y", function(d) {return y(d[1])-5; });
}
return hG;
}
// function to handle pieChart.
function pieChart(pD){
var pC ={}, pieDim ={w:250, h: 250};
pieDim.r = Math.min(pieDim.w, pieDim.h) / 2;
// create svg for pie chart.
var piesvg = d3.select(id).append("svg")
.attr("width", pieDim.w).attr("height", pieDim.h).append("g")
.attr("transform", "translate("+pieDim.w/2+","+pieDim.h/2+")");
// create function to draw the arcs of the pie slices.
var arc = d3.svg.arc().outerRadius(pieDim.r - 10).innerRadius(0);
// create a function to compute the pie slice angles.
var pie = d3.layout.pie().sort(null).value(function(d) { return d.freq; });
// Draw the pie slices.
piesvg.selectAll("path").data(pie(pD)).enter().append("path").attr("d", arc)
.each(function(d) { this._current = d; })
.style("fill", function(d) { return segColor(d.data.type); })
.on("mouseover",mouseover).on("mouseout",mouseout);
// create function to update pie-chart. This will be used by histogram.
pC.update = function(nD){
piesvg.selectAll("path").data(pie(nD)).transition().duration(500)
.attrTween("d", arcTween);
}
// Utility function to be called on mouseover a pie slice.
function mouseover(d){
// call the update function of histogram with new data.
hG.update(fData.map(function(v){
return [v.State,v.freq[d.data.type]];}),segColor(d.data.type));
}
//Utility function to be called on mouseout a pie slice.
function mouseout(d){
// call the update function of histogram with all data.
hG.update(fData.map(function(v){
return [v.State,v.total];}), barColor);
}
// Animating the pie-slice requiring a custom function which specifies
// how the intermediate paths should be drawn.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) { return arc(i(t)); };
}
return pC;
}
// function to handle legend.
function legend(lD){
var leg = {};
// create table for legend.
var legend = d3.select(id).append("table").attr('class','legend');
// create one row per segment.
var tr = legend.append("tbody").selectAll("tr").data(lD).enter().append("tr");
// create the first column for each segment.
tr.append("td").append("svg").attr("width", '16').attr("height", '16').append("rect")
.attr("width", '16').attr("height", '16')
.attr("fill",function(d){ return segColor(d.type); });
// create the second column for each segment.
tr.append("td").text(function(d){ return d.type;});
// create the third column for each segment.
tr.append("td").attr("class",'legendFreq')
.text(function(d){ return d3.format(",")(d.freq);});
// create the fourth column for each segment.
tr.append("td").attr("class",'legendPerc')
.text(function(d){ return getLegend(d,lD);});
// Utility function to be used to update the legend.
leg.update = function(nD){
// update the data attached to the row elements.
var l = legend.select("tbody").selectAll("tr").data(nD);
// update the frequencies.
l.select(".legendFreq").text(function(d){ return d3.format(",")(d.freq);});
// update the percentage column.
l.select(".legendPerc").text(function(d){ return getLegend(d,nD);});
}
function getLegend(d,aD){ // Utility function to compute percentage.
return d3.format("%")(d.freq/d3.sum(aD.map(function(v){ return v.freq; })));
}
return leg;
}
// calculate total frequency by segment for all state.
var tF = ['low','mid','high'].map(function(d){
return {type:d, freq: d3.sum(fData.map(function(t){ return t.freq[d];}))};
});
// calculate total frequency by state for all segment.
var sF = fData.map(function(d){return [d.State,d.total];});
var hG = histoGram(sF), // create the histogram.
pC = pieChart(tF), // create the pie-chart.
leg= legend(tF); // create the legend.
}
</script>
<script>
var freqData=[
{State:'AL',freq:{low:4786, mid:1319, high:249}}
,{State:'AZ',freq:{low:1101, mid:412, high:674}}
,{State:'CT',freq:{low:932, mid:2149, high:418}}
,{State:'DE',freq:{low:832, mid:1152, high:1862}}
,{State:'FL',freq:{low:4481, mid:3304, high:948}}
,{State:'GA',freq:{low:1619, mid:167, high:1063}}
,{State:'IA',freq:{low:1819, mid:247, high:1203}}
,{State:'IL',freq:{low:4498, mid:3852, high:942}}
,{State:'IN',freq:{low:797, mid:1849, high:1534}}
,{State:'KS',freq:{low:162, mid:379, high:471}}
];
dashboard('#dashboard',freqData);
</script>
http://plnkr.co/edit/URzbAymLSJs3t1zoZLdI?p=preview is plnkr created for the same.
I've tried as in this Accessing values from [Object][Object] data in D3.js but its not working for me.
Can anyone suggest me with the code .Thanks!

D3 - Reset Zoom when Chart is Brushed?

I'm working on a D3 timescale/pricescale financial chart. The chart SVG itself uses zoom() to pan and scale the data geometrically and re-draw the axes. Beneath the chart is an SVG brush pane which shows the entire data set at a high level and allows panning itself. The issue I'm facing is the same behavior as shown in this fiddle (not my code): http://jsfiddle.net/p29qC/8/. Zooming after brushing results in jumpy behavior because zoom() never picked up the changes from brush().
Zoom and brush work well independently, but I'm having trouble making them work together. When the chart is brushed, I'd expect zoom to detect that so the next time the chart is zoomed, it picks up where brush left off. And visa versa.
I've managed to set up a synchronization function to get the brush to update properly when zoom is initiated, but I can't get the reverse to work - update the chart zoom when brush occurs in the navigator. I've searched for hours to no avail. Are there any patches out there to fix this? My apologies for the long code blocks but I hope that it's helpful to set the context!
Setup code (some basic variables omitted for brevity):
// Create svg
var svg = d3.select('#chart')
.append('svg')
.attr({
class: 'fcChartArea',
width: width+margin.left+margin.right,
height: height+margin.bottom,
})
.style({'margin-top': margin.top});
// Create group for the chart
var chart = svg.append('g');
// Clipping path
chart.append('defs').append('clipPath')
.attr('id', 'plotAreaClip')
.append('rect')
.attr({
width: width,
height: height
});
// Create plot area, using the clipping path
var plotArea = chart.append('g')
.attr({
class: 'plotArea',
'clip-path': 'url(#plotAreaClip)'
});
// Compute mins and maxes
var minX = d3.min(data, function (d) {
return new Date(d.startTime*1000);
});
var maxX = d3.max(data, function (d) {
return new Date(d.startTime*1000);
});
var minY = d3.min(data, function (d) {
return d.low;
});
var maxY = d3.max(data, function (d) {
return d.high;
});
// Compute scales & axes
var dateScale = d3.time.scale()
.domain([minX, maxX])
.range([0, width]);
var dateAxis = d3.svg.axis()
.scale(dateScale)
.orient('bottom');
var priceScale = d3.scale.linear()
.domain([minY, maxY])
.nice()
.range([height, 0]);
var priceAxis = d3.svg.axis()
.scale(priceScale)
.orient('right');
// Store initial scales
var initialXScale = dateScale.copy();
var initialYScale = priceScale.copy();
// Add axes to the chart
chart.append('g')
.attr('class', 'axis date')
.attr('transform', 'translate(0,' + height + ')')
.call(dateAxis);
chart.append('g')
.attr('class', 'axis price')
.attr('transform', 'translate(' + width + ',0)')
.call(priceAxis);
// Compute and append the OHLC series
var series = fc.series.ohlc('path')
.xScale(dateScale)
.yScale(priceScale);
var dataSeries = plotArea.append('g')
.attr('class', 'series')
.datum(data)
.call(series);
// Create the SVG navigator
var navChart = d3.select('#chart')
.classed('chart', true)
.append('svg')
.classed('navigator', true)
.attr('width', navWidth + margin.left + margin.right)
.attr('height', navHeight+margin.top+margin.bottom)
.style({'margin-bottom': margin.bottom})
.append('g');
// Compute scales & axes
var navXScale = d3.time.scale()
.domain([minX, maxX])
.range([0, navWidth]);
var navXAxis = d3.svg.axis()
.scale(navXScale)
.orient('bottom');
var navYScale = d3.scale.linear()
.domain([minY, maxY])
.range([navHeight, 0]);
// Add x-axis to the chart
navChart.append('g')
.attr('class', 'axis date')
.attr('transform', 'translate(0,' + navHeight + ')')
.call(navXAxis);
// Add data to the navigator
var navData = d3.svg.area()
.x(function (d) {
return navXScale(new Date(d.startTime*1000));
})
.y0(navHeight)
.y1(function (d) {
return navYScale(d.close);
});
var navLine = d3.svg.line()
.x(function (d) {
return navXScale(new Date(d.startTime*1000));
})
.y(function (d) {
return navYScale(d.close);
});
navChart.append('path')
.attr('class', 'data')
.attr('d', navData(data));
navChart.append('path')
.attr('class', 'line')
.attr('d', navLine(data));
// create brush viewport
var viewport = d3.svg.brush()
.x(navXScale)
.on("brush", brush);
// add brush viewport to the SVG navigator
navChart.append("g")
.attr("class", "viewport")
.call(viewport)
.selectAll("rect")
.attr("height", navHeight);
// set zoom behavior
var zoom = d3.behavior.zoom()
.x(dateScale)
.scaleExtent([1, 12.99])
.on('zoom', zoom);
// Create zoom pane
plotArea.append('rect')
.attr('class', 'zoom-overlay')
.attr('width', width)
.attr('height', height)
.call(zoom);
Brush and zoom functions:
// zoom - brush synchronizations
function updateBrushFromZoom() {
if ((dateScale.domain()[0] <= minX) && (dateScale.domain()[1] >= maxX)) {
viewport.clear();
} else {
viewport.extent(dateScale.domain());
}
navChart.select('.viewport').call(viewport);
}
function updateZoomFromBrush() {
// help!!
}
function brush() {
var g = d3.selectAll('svg').select('g');
var newDomain = viewport.extent();
if (newDomain[0].getTime() !== newDomain[1].getTime()) {
dateScale.domain([newDomain[0], newDomain[1]]);
var xTransform = fc.utilities.xScaleTransform(initialXScale, dateScale);
// define new data set
var range = moment().range(newDomain[0], newDomain[1]);
var rangeData = [];
for (var i = 0; i < data.length; i += 1) {
if (range.contains(new Date(data[i].startTime*1000))) {
rangeData.push(data[i]);
}
}
// define new mins and maxes
var newMinY = d3.min(rangeData, function (d) {
return d.low;
});
var newMaxY = d3.max(rangeData, function (d) {
return d.high;
});
// set new yScale
priceScale.domain([newMinY, newMaxY]);
var yTransform = fc.utilities.yScaleTransform(initialYScale, priceScale);
// draw new axes on main chart
g.select('.fcChartArea .date.axis')
.call(dateAxis);
g.select('.fcChartArea .price.axis')
.call(priceAxis);
// transform the data to fit new chart viewport
g.select('.series')
.attr('transform', 'translate(' + xTransform.translate + ',' + yTransform.translate+ ')' + ' scale(' + xTransform.scale + ',' + yTransform.scale + ')');
}
else {
// remove transformation
g.select('.series')
.attr('transform', null);
}
updateZoomFromBrush();
}
// Zoom functions
function zoom() {
var g = d3.selectAll('svg').select('g');
// set new xScale
var newDomain = dateScale.domain();
var xTransformTranslate = d3.event.translate[0];
var xTransformScale = d3.event.scale;
// define new data set
var range = moment().range(newDomain[0], newDomain[1]);
var rangeData = [];
for (var i = 0; i < data.length; i += 1) {
if (range.contains(new Date(data[i].startTime*1000))) {
rangeData.push(data[i]);
}
}
// define new max and min
var newMinY = d3.min(rangeData, function (d) {
return d.low;
});
var newMaxY = d3.max(rangeData, function (d) {
return d.high;
});
// set new yScale
priceScale.domain([newMinY, newMaxY]);
var yTransform = fc.utilities.yScaleTransform(initialYScale, priceScale);
// draw new axes on main chart
g.select('.fcChartArea .date.axis')
.call(dateAxis);
g.select('.fcChartArea .price.axis')
.call(priceAxis);
// transform the data to fit new chart viewport
g.select('.series')
.attr('transform', 'translate(' + xTransformTranslate + ',' + yTransform.translate+ ')' + ' scale(' + xTransformScale + ',' + yTransform.scale + ')');
// update SVG navigator
updateBrushFromZoom();
}
Helper functions:
fc.utilities.yScaleTransform = function(oldScale, newScale) {
var oldDomain = oldScale.domain();
var newDomain = newScale.domain();
var scale = (oldDomain[1] - oldDomain[0]) / (newDomain[1] - newDomain[0]);
var translate = scale * (oldScale.range()[1] - oldScale(newDomain[1]));
return {
translate: translate,
scale: scale
};
};
fc.utilities.xScaleTransform = function(oldScale, newScale) {
var oldDomain = oldScale.domain();
var newDomain = newScale.domain();
var scale = (oldDomain[1] - oldDomain[0]) / (newDomain[1] - newDomain[0]);
var translate = scale * (oldScale.range()[0] - oldScale(newDomain[0]));
return {
translate: translate,
scale: scale
};
};
In updateZoomFromBrush(), rebind the scale to the zoom behavior with zoom.x(dateScale).
This is needed because d3.behavior.zoom() operates on a copy of the scale you pass in, so without rebinding the scale, the behavior won't have any of the changes made to the scale's domain in brush().
See this example http://bl.ocks.org/mbostock/3892928

Categories