Reputation: 37
I am trying to implement a tooltip for a line chart. The chart is displaying correctly.On hovering on the chart it is giving the error "Cannot read property time of undefined" I am using d3 version 3.
Code is:
function lineChart(data, id){
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 1000 - margin.left - margin.right,
height = 370 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Define the div for the tooltip
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.loadaverage); });
// Adds the svg canvas
var svg = d3.select(id)
.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 + ")");
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain([0, d3.max(data, function(d) { return d.loadaverage; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data))
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(d.time + "<br/>" + d.loadaverage)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
}
Upvotes: 0
Views: 711
Reputation: 5443
I guess you never bind your svg element with your data. That step is usually done by calling the following lines on the selection you are creating:
.data(your_data)
.enter() // You are now entering to the selection bound to 'your_data'
So because your data and your svg elements are not bound, on the line
.on("mouseover", function(d) {
d
is undefined.
You can try to fix it by binding your data this way :
svg.selectAll('path')
.data(data)
.enter()
.append("path")
.attr("class", "line")
// your code logics continues here
If needed you can see d3 documentation or Scott Murray’s guide to data binding for example.
Upvotes: 1