tooltip D3
by sunnycyk
HTML
<div id="graph"></div>
CSS
body {
margin: 0;
padding: 0;
}
path {
stroke: steelblue;
stroke-width: 1;
fill: none;
}
.axis {
shape-rendering: crispEdges;
}
.x.axis line {
stroke: lightgrey;
}
.x.axis .minor {
stroke-opacity: .5;
}
.x.axis path {
display: none;
}
.y.axis line, .y.axis path {
fill: none;
stroke: #000;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 14px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
JavaScript
var m = [80, 80, 80, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 400 - m[0] - m[2]; // height
// create a simple data[0] array that we'll plot with a line (this array represents only the Y values, X will just be the index location)
var data = [
[200, 32, 566, 124, 22, 154],
[124, 22, 154, 200, 32, 566]
];
var max_value = d3.max(data[0]);
// X scale will fit all values from data[] within pixels 0-w
var x = d3.scale.linear().domain([0, data[0].length - 1]).range([0, w]);
// Y scale will fit values from 0-10 within pixels h-0 (Note the inverted domain for the y-scale: bigger is up!)
var y = d3.scale.linear().domain([0, max_value]).range([h, 0]);
var toolTipScale = d3.scale.linear().domain([h + 80, 80]).range([0, max_value]);
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var line = d3.svg.line()
.x(function (d, i) {
return x(i);
})
.y(function (d) {
return y(d);
});
// Add an SVG element with the desired dimensions and margin.
var graph = d3.select("#graph").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
// create yAxis
var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);
// Add the x-axis.
graph.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
// create left yAxis
var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
// Add the y-axis to the left
graph.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(-25,0)")
.call(yAxisLeft);
// Add the line by appending an svg:path element with the data[0] line we created above
// do this AFTER the axes above so that...