ng150716
ng150716

Reputation: 2244

Spacing Bars on Chart using JavaScript/D3

I am using D3 and data I have stored in a JSON format to plot a bar chart. However, all by bars appear to be in the left hand side of the chart, and as a result I can only see the bar for the highest value in my data set.

Here are the relevant parts of my JavaScript code:

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

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

var parseDate = d3.time.format("%Y-%m-%d").parse;

d3.json("performance/api", function (data) {

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

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

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

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.date); })
      .attr("width", width/data.length)
      .attr("y", function(d) { return y(d.percent_return); })
      .attr("height", function(d) { return height - y(d.percent_return); });

Additionally here is the sample of one of my data entries:

[{"percent_return": "12.00", "date": "2016-01-02T01:43:52Z"},

Any ideas on how I can properly parse the date and plot it on my x-axis? Thanks.

Upvotes: 1

Views: 44

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You are parsing the date incorrectly:

Instead of

var parseDate = d3.time.format("%Y-%m-%d").parse;

use

parseDate = d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse

Read here for date format in d3

Upvotes: 2

Related Questions