Exploring the world of D3 for the first time and following a tutorial on creating a flexible chart that adjusts to the width and height regardless of the number of bars ('The new Chart').
Struggling with using personal data, here's the simplified code from the tutorial for making a bar chart:
var w = 500;
var h = 100;
var barPadding = 1;
var data = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / data.length);
})
.attr("y", function(d) {
return h - (d * 4);
})
.attr("width", w / data.length - barPadding)
.attr("height", function(d) {
return d * 4;
});
The issue might be related to the 'data.length' segment in the tutorial's code:
.attr("x", function(d, i) {return i * (w / data.length);
Alternatively, it could be how I'm accessing 'time' from my dataset. Here's my code snippet:
<div id="chart">
<svg width="800" height="600"><g class="group"></g>
</svg>
</div>
var w = 500;
var h = 100;
var barPadding = 1;
var data = [
{"name": "The Kings speech", "time": 118},
{"name": "Slumdog Millionaire", "time": 120},
{"name": "Shakespeare in Love", "time": 122},
{"name": "Chariots of Fire", "time": 123},
]
d3.select('svg g.group')
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', function(d, i) {return i * (w / data.length)})
.attr('y', function(d) {return h - d['time'];})
.attr('width', w / data.length - barPadding)
.attr('height', function(d) {return d['time'];})
Seeking guidance to overcome this hurdle, any help would be greatly appreciated! Thank you.