Skip to content Skip to sidebar Skip to footer

Plot A Graph Using D3.js

I am trying to plot a graph using D3.js. file.json is my JSON file. Date-Time should be in the X-Axis and Sales should be in Y-Axis. This is my JSON Structure, [ { D

Solution 1:

Here is an example of what you might want (taken from: https://bl.ocks.org/mbostock/3883245)

var data = [
    {
        Date : "2017-12-17 18:30:01",
        Sales : "50"

    },
    {   Date : "2017-12-17 17:30:00",
        Sales : "20"

    },
    {
        Date : "2017-12-17 16:30:00",
        Sales : "10"
    }
].map(function(entry) {
  return {
    Date: d3.timeParse("%Y-%m-%d %H:%M:%S")(entry.Date),
    Sales: +entry.Sales
  }
});

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleTime()
    .rangeRound([0, width]);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var line = d3.line()
    .x(function(d) { returnx(d.Date); })
    .y(function(d) { returny(d.Sales); });

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

g.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))

g.append("g")
    .call(d3.axisLeft(y))

g.append("path")
    .datum(data)
    .attr("fill", "none")
    .attr("stroke", "steelblue")
    .attr("stroke-linejoin", "round")
    .attr("stroke-linecap", "round")
    .attr("stroke-width", 1.5)
    .attr("d", line);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"></script>'

<svgwidth="600"height="180"></svg>

Post a Comment for "Plot A Graph Using D3.js"