d3.tip example

by Nayana Das

HTML

<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

background: none repeat scroll 0 0 #ffffff;

CSS

.line {
    fill: none;
    stroke: steelblue;
    stroke-width: 1.5px;
}
.circle {
    fill: white;
    stroke: steelblue;
    stroke-width: 1.5px;
}
.axis {
    fill: none;
    stroke: black;
}
text {
    font: normal 12px sans-serif;
}

JavaScript

var data = [{
     date: "1-jan-12",
     close: 5
 }, {
     date: "1-Feb-12",
     close: 100
 }, {
     date: "1-mar-12",
     close: 150
 }, {
     date: "1-apr-12",
     close: 90
 }, {
     date: "1-May-12",
     close: 34
 }, {
     date: "1-jun-12",
     close: 67
 }, {
     date: "1-jul-12",
     close: 67
 }, {
     date: "1-Aug-12",
     close: 79
 }];
 var margin = {
     top: 20,
     right: 20,
     bottom: 30,
     left: 50
 },
 width = 460 - margin.left - margin.right,
     height = 200 - margin.top - margin.bottom;

 var parseDate = d3.time.format("%d-%b-%y").parse;

 var x = d3.time.scale()
     .range([0, width]);

 var y = d3.scale.linear()
     .range([height, 0]);

 var xAxis = d3.svg.axis()
     .scale(x)
     .orient("bottom");

 var yAxis = d3.svg.axis()
     .scale(y)
     .orient("left");

 var line = d3.svg.line()
     .x(function (d) {
     return x(d.date);
 })
     .y(function (d) {
     return y(d.close);
 });

 var tip = d3.tip()
     .attr('class', 'd3-tip')
     .offset([-10, 0])
     .html(function (d) {
         return "<span style='background-color: yellow'><strong>Price($):</strong> <span style='color:red'>" + d.close + "</span></span>";
 })

 var svg = d3.select("body").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 + ")");
 svg.call(tip);

 data.forEach(function (d) {
     d.date = parseDate(d.date);
     d.close = +d.close;
 });

 x.domain(d3.extent(data, function (d) {
     return d.date;
 }));
 y.domain(d3.extent(data, function (d) {
     return d.close;
 }));

 svg.append("g")
     .attr("class", "x axis")
     .attr("transform", "translate(0," + height + ")")
     .call(xAxis);

 svg.append("g")
     .attr("class", "y axis")
     .call(yAxis)
     .append("text")
     .attr("transform", "rotate(-90)")
     .attr("y", 6)
     .attr("dy", ".71em")
    ...