javascript - d3 convert bar chart to grouped bar chart -
i have d3 bar chart lists data based on date in order day. works great, need display 2 sets of data per day, in grouped bar chart format or side-by-side bars.
i'm thinking take bit of refactoring after fooling , referencing bunch of examples i've found on net, fact chart using timescale , linear scale throws wrench in understanding of this. i'm hoping can show me way making chart show 2 bars each day in chart.
my current x axis setup:
var xtimescale = d3.time.scale(). domain([new date(data[0].date), d3.time.day.offset(new date(data[data.length - 1].date), 1)]) .range([0, width]); var xscale = d3.scale.linear() .domain([0, data.length]) .range([0, width]);
my fiddle: http://jsfiddle.net/mmejf/45/
so 2 separate sets of data, need have 2 bars per day - each bar representing value each data set. how can accomplish displaying grouped bars? , better if datasets combined one?
first, lets think 2 separate graphs of 2 sets of data. scales same. this:
ok. that's , good, how there stacked chart?
well, need make sure each tick has both pieces of data.
then, when plotting each tick, should have first piece of data plotted 0, , second should plotted not zero, offset amount of first data.
with in mind, other pieces fall place: y axis must 0 max of sum of 2 pieces of data.
var data = [{"year":2013,"month":3,"day":5,"count1":18, "count2":3}, {"year":2013,"month":3,"day":6,"count1":3, "count2":11}, {"year":2013,"month":3,"day":7,"count1":10,"count2": 8}, {"year":2013,"month":3,"day":8,"count1":18, "count2": 4}]; var maxvalue = d3.max(data, function (d) { return d.count1 + d.count2; }); var yscale = d3.scale.linear() .domain([0, maxvalue]) .range([0, height]);
now, it's easier treat each set of bars group, , add bars group:
var bars = svg.selectall(".bar") .data(data).enter() .append("g") .attr("class","bar") .attr("transform", function(d){ return "translate("+xtimescale(d.date)+",0)" }); var count1bars = bars.append("rect") .attr("class", "count1") .attr("height", function(d){return yscale(d.count1)}) .attr("y", function(d){return height - yscale(d.count1)}) .attr("width", barwidth); var count2bars = bars.append("rect") .attr("class", "count2") .attr("height", function(d){return yscale(d.count2)}) .attr("y", function(d){return height - yscale(d.count1) -yscale(d.count2)}) .attr("width", barwidth); var count1text = bars.append("text") .text(function(d){return d.count1}) .attr("y", function(d){return height}) .attr("x", barwidth / 2); var count2text = bars.append("text") .text(function(d){return d.count2}) .attr("y", function(d){return height - yscale(d.count1)}) .attr("x", barwidth / 2);
now, rough example on way: http://jsfiddle.net/mmejf/49/
good luck! think need, , things tend fall place there!
Comments
Post a Comment