I am trying to get d3 to draw a single histogram, like this:
<svg width = '500' height= '100'> <rect x='0' y='0' width='224' height='30' fill='green'/> <rect x='224' y='0' width='84' height='30' fill='blue'/> <rect x='308' y='0' width='29' height='30' fill='darkgray'/> <rect x='337' y='0' width='3' height='30' fill='#606060'/> </svg>
As you can see, the x position starts from zero, then each subsequent x position is equal to the sum of the previous widths.
So, I'm trying to get d3 to draw something like this from an array called datavars:
var datavars = [224, 84, 29, 3];
... and so that d3 assigns the correct width value to the correct x value, I created these variables:
var prev_width0 = 0; var prev_width1 = datavars[0]; var prev_width2 = datavars[0] + datavars[1]; var prev_width3 = datavars[0] + datavars[1] + datavars[2];
... and define the value of x as follows:
//create SVG element var svg = d3.select('body') .append('svg') .attr('width', w) .attr('height', h); svg.selectAll('rect') .data(datavars) .enter() .append('rect') .attr('width', function(d){ return d;}) .attr('x',function(d, i){ return 'prev_width'+i; }) .attr('y',0) .attr('height', 30);
As you might have guessed, a strongly backing function (based on the sum of the previous widths and defined in the prev_width variables) returns a string for each iteration (prev_width0, prev_width1, etc.) and not the values ββthat I thought I determined when i created prev_width variables.
I, obviously, incorrectly define variables. Any idea how I can do this right?