Reputation: 13
I am new to d3.js and is currently making a simple bar chart in version 4. I understand the basic idea of a scale. The problem is whenever I reload my page, some of my bars on my bar chart are cut in half, or is moved all the way to the top(or bottom) this is my code. I want my bars to stay within the svg but if i were to put for example
.attr(height, function(d){ return yScale(d)]);
It wont work. Any ideas? my code should be located on the bottom.
var data = [ 40,60,80,100,600,700];
var height = 500, width = 500;
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height",height);
var yScale = d3.scaleLinear()
.domain([40, 700])
.range([0,400]);
var bars = canvas.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", 30)
.attr("height", function(d){ return yScale(d)})
.attr("x", function(d,i){ return i * 35})
.attr("y", function(d) { return height - d});
}
Output of image is here.
Upvotes: 0
Views: 1101
Reputation: 102194
The problem here is this line:
.attr("y", function(d) {
return height - d
});
Why are you using the raw data value? You have to use the value returned by the scale:
.attr("y", function(d) {
return height - yScale(d)
});
Here is the updated code:
var data = [40, 60, 80, 100, 600, 700];
var height = 500,
width = 500;
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var yScale = d3.scaleLinear()
.domain([40, 700])
.range([0, 400]);
var bars = canvas.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", 30)
.attr("height", function(d) {
return yScale(d)
})
.attr("x", function(d, i) {
return i * 35
})
.attr("y", function(d) {
return height - yScale(d)
});
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 1