Line charts using d3.js with customized tooltip

by Mansi Arora

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js"></script>
<div id="chartArea" style="margin: 10px;"></div>

CSS

div.tooltip {
  position: absolute;
  text-align: center;
  width: 90px;
  height: 30px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  pointer-events: none;
}

JavaScript

function drawLineChart() {

  //Step 1 : Fetch Data
  var lineData = getChartData();

  // Step 2 : Add SVG with attr id equals to 'visualisation'
  var margin = {
      top: 100,
      right: 100,
      bottom: 100,
      left: 100
    },
    width = 1000,
    height = 500;
  createSvg(width, height);

  // Step 3 : Define scale and axes
  var mySVG = d3.select("#visualisation"),

    xScale = d3.scale.linear().range([margin.left, width - margin.right]).domain([0, 100]),
    yScale = d3.scale.linear().range([height - margin.top, margin.bottom]).domain([0, 100]),

    xAxis = d3.svg.axis().scale(xScale),
    yAxis = d3.svg.axis().scale(yScale).orient('left'); // y-axis it needs to be oriented to the left

  //Step 4 :  Append both the axis to the SVG and apply the transformation
  mySVG.append("g") //g element is used to group SVG shapes together
    .attr("class", "x-axis")
    .attr("transform", "translate(0," + (height - margin.bottom) + ")") //The transforms are SVG transforms
    .call(xAxis) //  When you use "call" on a selection you are calling the function passed in (xAxis) on the elements (g) of the selection.
    .append("text")
    .attr("y", '3em')
    .attr("x", "30em")
    .text("Quantity");
  // The translate() function takes one or two values which specify the horizontal and vertical translation values, respectively.
  // tx represents the translation value along the x-axis;
  // ty represents the translation value along the y-axis.

  mySVG.append("g") //We create an SVG Group Element to hold all the elements that the axis function produces.
    .attr("class", "y-axis")
    .attr("transform", "translate(" + (margin.left) + ",0)")
    .call(yAxis)
    .append("text")
    .attr("y", "16em")
    .attr("x", "-5.5em")
    .text("Price ($)");
  //We have transformed both the axes, keeping the defined margins in view so that the axes don’t touch the SVG margins.

  // Step 5 : Plot coordinates and draw a line.
  var path = drawLine(mySVG, xScale,...