D3 Graph - changing y-axis to integer - javascript

I'm trying to create integer bands in the y axes.
Have tried changing .scaleband to .scalelinear and .ticks "arbitraryMetric" is stored as an integer.
Code:
const categories = vizData.map(d => d.arbitraryMetric);
const yScale = d3
.scaleBand()
.domain(categories)
.range([0, vizHeight - timelineMargin.bottom]);
const labels = vizCanvas
.selectAll('text')
.data(categories)
.enter()
.append('text')
.style('font-family', style.fontFamily)
.style('fill', '#3C4043')
.attr('x', timelineMargin.left - 10)
.attr('y', d => yScale(d) + yScale.bandwidth() / 2)
.attr('text-anchor', 'end')
.text(d => d);

This following solution will do the trick - credit to this answer
const yAxisTicks = yScale.ticks()
.filter(tick => Number.isInteger(tick));
const yAxis = d3.axisLeft(yScale)
.tickValues(yAxisTicks)
.tickFormat(d3.format('d'));

Related

Bar graph bleeding below y axis D3.js

I can't figure out why my elements are bleeding into the bottom padding. It is preventing me from having a elements. I am sure it is something simple, it always is. I just can't figure out what's wrong. I have tried changing the height and the scales, but it just changes things I don't want changed. I keep looking at tutorials on scales and I haven't found anything that seems off. If I get I have the project on codepen, here is the link: https://codepen.io/critchey/pen/YzEXPrP
Here is a screen shot to know what I am talking about:
Here is the javascript:
//Mapping dataset to its x and y axes
const xData = dataset.map(d => {
let date = new Date(d[0]);
return date;
});
const xDates = xData.map(d => {
let dateFormatted = d.toLocaleString("default", {month: "short"}) + ' ' + d.getDate() + ', ' + d.getFullYear()
return dateFormatted;
});
const yData = dataset.map(d => d[1]);
//Variable for use inside D3
const h = 400;
const w = 800;
const pad = 40;
//Scales for the SVG element
const xDateScale = d3.scaleTime()
.domain([0, w])
.range([pad, w - pad]);
const xScale = d3.scaleLinear()
.domain([0, yData.length])
.range([pad, w - pad]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(yData, (d) => d)])
.range([h - pad, pad]);
//Declaring the SVG element
const svg = d3.select('#svg-container')
.append('svg')
.attr('width', w)
.attr('height', h)
//Declaring each bar
svg.selectAll('rect')
.data(yData)
.enter()
.append('rect')
.attr('x', (d, i) => xScale(i))
.attr('y', (d, i) => yScale(d))
.attr("width", w / (yData.length - pad * 2))
.attr("height", (d, i) => d)
.attr("class", "bar")
.append('title')
.text((d, i) => 'GDP: ' + d + ' | Date: ' + xDates[i])
//Axes Declarations
const xAxis = d3.axisBottom(xDateScale);
const yAxis = d3.axisLeft(yScale);
svg.append("g")
.attr("transform", "translate(0," + (h - pad / 2) + ")")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + pad + ",0)")
.call(yAxis)
The problem is that you're not using the correct value with the height attribute for your rects
Just make the following change and it should work:
.attr("height", (d, i) => yScale(0) - yScale(d))

How can I make a bar chart starting from the 0 point of the y axis and not from the bottom of the svg?

I'm trying to make a bar chart but I can't figure out a way to make the bar start from the 0 point of y axis and not from the very bottom of the svg. How can I fix that?
let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";
const padding = 50;
const height = 460;
const width = 900;
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height);
var arr = [];
d3.json(url, function(data) {
for (let i = 0; i < data.data.length; i++) arr[i] = data.data[i];
const yScale = d3.scaleLinear()
.domain([0, d3.max(arr, (d) => d[1])])
.range([height - padding, padding]);
const yAxis = d3.axisLeft(yScale);
svg.append('g')
.attr('transform', 'translate(' + padding + ', 0)')
.call(yAxis)
svg.selectAll('rect')
.data(arr)
.enter()
.append('rect')
.attr('fill', 'blue')
.attr('height', d => d[1] + padding)
.attr('width', 2.909090909090909)
.attr('x', (d, i) => padding + (3.2 * i))
.attr('y', d => yScale(d[1]))
.append('title')
.text(d => d[1])
});
<script src="https://d3js.org/d3.v4.min.js"></script>
You are incorrectly calculating the height of the rectangle, and not using your scale. It's also trickier since your use of padding is not the typical D3 convention.
svg.selectAll('rect')
.data(arr)
.enter()
.append('rect')
.attr('fill', 'blue')
.attr('height', d => height - padding - yScale(d[1]))

render bar charts in javascript using svg and 2D array from json

Have spent the last 2 days looking through stackoverflow and online examples as to why my charts aren't displaying properly.
I'm sure I'm missing something in terms of the scaling portion of the code. If I copy the dark part at the bottom of the x-Axis on the chart to notepad it gives me all of the x-axis elements.
Can anyone point me in the right direction?
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.8.0/d3.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded',function(){
req.open("GET",'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('title')[0].innerHTML=json.name;
dataset=json.data;
const w = 500;
const h = 300;
const padding = 10;
// create an array with all date names
const dates = dataset.map(function(d) {
return d[0];
});
const xScale = d3.scaleBand()
.rangeRound([padding, w-padding])
.padding([.02])
.domain(dates);
console.log("Scale Bandwidth: " + xScale.bandwidth());
const yScale = d3.scaleLinear()
.rangeRound([h-padding, padding])
.domain(0,d3.max(dataset, (d)=>d[1]));
console.log("Dataset Max Height: " + d3.max(dataset, (d)=>d[1]));
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width",(d,i)=>xScale.bandwidth())
.attr("height",(d,i)=>(h-yScale(d[1])))
.attr("x", (d,i)=>xScale(d[0]))
.attr("y", (d,i)=>yScale(d[1]))
.attr("fill", "navy")
.attr("class", "bar");
};
});
</script>
<h1 class="title">Title Will Go Here</h1>
</body>
D3 now uses Promises instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support async and await.
Changes in D3 5.0
Also, you are right in that your yScale is broken. Linear scales need a range and a domain, each being passed a 2 value array.
const yScale = d3.scaleLinear()
.range([h - padding, padding])
.domain([0, d3.max(dataset, (d) => d[1])]);
document.addEventListener('DOMContentLoaded', async function() {
const res = await d3.json("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json");
//console.log(res.data)
const dataset = res.data
const w = 500;
const h = 300;
const padding = 10;
// create an array with all date names
const dates = dataset.map(function(d) {
return d[0];
});
const max = d3.max(dataset, function(d) { return d[1]} )
const xScale = d3.scaleBand()
.rangeRound([0, w])
.padding([.02])
.domain(dates);
console.log("Scale Bandwidth: " + xScale.bandwidth());
const yScale = d3.scaleLinear()
.range([h - padding, padding])
.domain([0, d3.max(dataset, (d) => d[1])]);
console.log("Dataset Max Height: " + d3.max(dataset, (d) => d[1]));
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", (d, i) => xScale.bandwidth())
.attr("height", (d, i) => (h - yScale(d[1])) )
.attr("x", (d, i) => xScale(d[0]))
.attr("y", (d, i) => yScale(d[1]))
.attr("fill", "navy")
.attr("class", "bar");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.8.0/d3.min.js"></script>
Codepen

How to increase the axis?

I make vertical histogram. The center of the axes is located in the left bottom corner.
JSFIDDLE
But last bar went beyond the x-axis limit (point [700, 400]). I need increase x-axis. Please help me.
My svg element:
const svg = d3.select('#svg');
My axis:
xScale = d3.scaleLinear()
.domain([
d3.min(points, d => d[0]),
d3.max(points, d => d[0])
])
.range([paddings.left, width - paddings.right]);
yScale = d3.scaleLinear()
.domain([
d3.min(points, d => d[1]),
d3.max(points, d => d[1])
])
.range([height - paddings.bottom, 0 + paddings.top]);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
svg.append('g')
.attr('class', 'x-axis-group')
.attr('transform', 'translate(0,' + (height - paddings.bottom) + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y-axis-group')
.attr('transform', 'translate(' + paddings.left + ',0)')
.call(yAxis);
My bars:
svg.selectAll(null)
.data(points)
.enter('')
.append('rect')
.attr('x', d => xScale(d[0]))
.attr('y', d => yScale(d[1]))
.attr('width', width / points.length)
.attr('height', d => height - yScale(d[1]) - paddings.bottom)
If the bars on your chart are 100 units wide, the maximum x value should be d3.max(points => d[0]) + 100. If you plug that into your scale, you will find your chart now covers the correct range.
xScale = d3.scaleLinear()
.domain([
d3.min(points, d => d[0]),
d3.max(points, d => d[0]) + 100
])
.range([paddings.left, width - paddings.right]);
You will now find that you have made a mistake in calculating the width of the bars:
svg.selectAll(null)
.data(points)
.enter('')
.append('rect')
.attr('x', d => xScale(d[0]))
.attr('y', d => yScale(d[1]))
.attr('width', width / points.length)
.attr('height', d => height - yScale(d[1]) - paddings.bottom)
Can you work out why they are too wide?

D3 scales mess up my bar chart

I'm writing a simple bar chart that draws a rect element for each piece of data. This is a part of my code without scales, which works fine:
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => (i*4))
.attr("y", (d) => h - d[1]/50)
However, if I add y-scale, my bars flip over, and if I add x-scale, I can only see one bar. Here's my code with scales:
const xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[0])])
.range([padding, w - padding]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, (d) => d[1])])
.range([h - padding, padding]);
//some other code
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => xScale(i*4))
.attr("y", (d) => yScale(d[1]/50))
Here's my CodePen with scales, that's what it looks like: http://codepen.io/enk/pen/vgbvWq?editors=1111
I'd be really greatful if somebody told me what am I doing wrong.
D3 scales are not messing with your chart. The problem here is simple.
Right now, this is your dataset:
[["1947-01-01", 243.1], ...]
As you can see, d[0] is a string (representing a date), not a number. And, in d3.scaleLinear, the domain is an array with two values only.
The solution here is using a scaleBand instead:
const xScale = d3.scaleBand()
.domain(dataset.map(d => d[0]))
.range([padding, w - padding]);
And changing the code of the rectangles to actually use the scales (I made several changes, check them):
const rect = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", xScale.bandwidth())
.attr("x", (d => xScale(d[0]))) //xScale
.attr("height", (d => h - yScale(d[1]))) //yScale
.style("y", (d => yScale(d[1])))
.attr("data-date", (d) => d[0])
.attr("data-gdp", (d) => d[1])
.attr("class", 'bar')
Here is your updated CodePen: http://codepen.io/anon/pen/NdJGdo?editors=0010

Categories

Resources