Codepen link: https://codepen.io/AronNaylor/pen/RwWProy?editors=0010
Project link: https://www.freecodecamp.org/learn/data-visualization/data-visualization-projects/visualize-data-with-a-bar-chart
I think I am going wrong with how the data is being passed into the d3 functions, but now I’ve hit a wall, my chart is off the axis, my axis don’t correspond to the dataset that’s been passed into them and I have have absolutely no idea why.
var height = 600;
var width = 650;
var margin = ({top: 20, right: 20, bottom: 20, left: 40});
d3.json('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json').then(data => {
// map data into relevant arrays
const gdpData = data.data.map(d => d[1]);
const dates = data.data.map(d => d[0]);
const axisDates = dates.map(each => each.slice(0, 4));
// set scales
var xScale = d3.scaleBand()
.domain([d3.min(axisDates), d3.max(axisDates)])
.range([margin.left, width - margin.right]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(gdpData)])
.range([height - margin.bottom, margin.top]);
var xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale));
var yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale));
// initialise svg height, width & padding
var svg = d3.select('svg')
.attr('height', height)
.attr('width', width);
svg
.append('g')
.call(yAxis);
svg
.append('g')
.call(xAxis);
// append a rect for each data value - GDP data
d3.select('svg')
.selectAll('rect')
.data(gdpData)
.enter()
.append('rect')
.attr('class', 'bar')
.attr('x', (d, i) => i)
.attr('y', (d, i) => yScale(d))
.style('height', (d) => height - yScale(d))
.style('width', 10) // alter this will change how the bars are plotted
});
See the Pen Plotted Bar Chart D3 by Aron (@AronNaylor) on CodePen.