简体   繁体   中英

D3 bar chart and html data attributes

I have a D3 zoomable bar chart, this is the current data that's being passed in to the chart:

var data = [{"date":"2012-03-20","total":3},{"date":"2012-04-21","total":8},{"date":"2012-05-22","total":2},{"date":"2012-06-23","total":10},
{"date":"2012-07-24","total":3},{"date":"2012-08-25","total":20},
{"date":"2012-09-26","total":12},{"date":"2012-10-23","total":10},
{"date":"2012-11-24","total":3},{"date":"2012-12-25","total":20},{"date":"2012-12-26","total":12}];

What i want to do is pass data attributes:

<div class="test">
  <div class"red" data-name"bar1" data-date="2012-03-20" data-total="6">
  </div>
  <div class="blue" data-name="bar2" data-date="2012-04-21" data-total="10">
 </div>

</div>

I want the dates and values to be obtained from "data-date" and "data-value". What relevant changes do i need to make to the "x" and "y" variable.

They are currently like so:

var x = d3.time.scale()
    .domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
    .rangeRound([0, width - margin.left - margin.right]);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d) { return d.total+ (d.total/4); })])

Full code can be found here: https://jsfiddle.net/noobiecode/wck4ur9d/49/

Any help would be much appreciated.

No need for jquery , d3 has it covered:

var data = [];
d3.selectAll(".test>div")
  .each(function() {
    var self = d3.select(this);
    data.push({
      date: self.attr("data-date"),
      total: +self.attr("data-value")
    });
  });

Updated fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM