score:0

Accepted answer

The list of the problems:

  1. Your reference to D3 is v3. However, your code uses v4.
  2. You are defining the axes generators before defining the scales.
  3. You are not translating the axes.

Besides that, there is no such a thing as "JSON array". That's just an array. You probably meant hardcoded data

Here is the working code:

var data = [{
  date: "1999-06-23",
  value: 1
}, {
  date: "1999-06-24",
  value: 2
}, {
  date: "1999-06-28",
  value: 3
}, {
  date: "1999-06-29",
  value: 4
}, {
  date: "1999-06-30",
  value: 5
}];

var parseDate = d3.timeParse("%Y-%m-%d");

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

var svg = d3.select("body").append("svg")
  .attr("width", 956)
  .attr("height", 360);

var margin = {
    top: 50,
    right: 100,
    bottom: 50,
    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.scaleBand().rangeRound([0, width]).paddingInner(0.05);
var y = d3.scaleLinear().range([height, 0]);

x.domain(data.map(function(d) {
  return d.date;
}));
y.domain([0, d3.max(data, function(d) {
  return d.value;
})]);

var xAxis = d3.axisBottom(x)
  .tickFormat(d3.timeFormat("%Y-%m-%d"));

var yAxis = d3.axisLeft(y)
  .ticks(10);

g.selectAll("bar")
  .data(data)
  .enter().append("rect")
  .style("fill", "steelblue")
  .attr("x", function(d) {
    return x(d.date);
  })
  .attr("y", function(d) {
    return y(d.value);
  })
  .attr("width", x.bandwidth())
  .attr("height", function(d) {
    return height - y(d.value);
  });

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(" + margin.left + "," + (height + margin.bottom) + ")")
  .call(xAxis)
  .selectAll("text")
  .style("text-anchor", "end")
  .attr("dx", "-.8em")
  .attr("dy", "-.55em")
  .attr("transform", "rotate(-90)");

svg.append("g")
  .attr("class", "y axis")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Value ($)");
<script src="https://d3js.org/d3.v4.min.js"></script>


Related Query