Can someone tell me why my bars start below the bottom axis? Am I utilizing the x and y Scales correctly? I feel like i should be creating seperate scales for the actual data itself and a scale for the axis…does that make sense?
const url =
"https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";
// Remember DOMContentloaded as an event listener
// ...to put bars right side up: height of svg - height of bar
// This is how I get the data that I need into a variable for later refernce
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send();
var dataSet = JSON.parse(req.responseText);
const w = 1000; //this sets my dimensions for the svg canvas
const h = 600;
const padding = 60;
const svg = d3 //this is my svg canvas
.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// Must create scales to scale the data itself accordingly as well for the guides and ticks
// xScale
// yScale
// xTimeTicks
// yLineTicks
// must define your scales before you use them!
const yScale = d3
.scaleLinear()
.domain([
0,
d3.max(dataSet["data"], d => d[1])
])
.range([h,padding]);
// you need a time scale to cover the full width of the canvas or the area you want to cover
const xScale = d3
.scaleTime()
.domain([new Date(dataSet['from_date']), new Date(dataSet['to_date'])])
.range([padding, w]);
// Basically have all rectangles being printed except the data needs to be scaled, need to craate a yScale
d3
.select("svg")
.selectAll("rect")
.data(dataSet["data"])
.enter()
.append("rect")
.attr("class", "bar")
.attr("width", 2)
.attr("height", d => d[1])
.attr("x", (d, i) => i) //how to get bars to stretch to end of canvas or canvas - padding
.attr("y", (d, i) =>yScale(d[1]) )
.attr('transform', `translate(${padding}, ${-padding})`);
const xAxis = d3.axisBottom(xScale)
svg
.append("g")
.attr("id", "x-axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
const yAxis = d3.axisLeft(yScale);
svg
.append("g")
.attr("id", "y-axis")
.attr("transform", `translate(${padding} , ${-padding})`) //translates it 60px right and 60px up
.call(yAxis);
Here is the link to the pen: https://codepen.io/anon/pen/vQeBQx/?editors=0010