I’m trying to add the axis to my bar chart and transform my bar chart horizontal view to a vertical one. This is my chart:
<!DOCTYPE html>
<html>
<head>
<head>
<title>Title</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>
// Append svg space
d3.json("csvjson.json", function (data) {
var canvas = d3.select("body").append("svg")
.attr("width", 1500)
.attr("height", 1500)
//Drawing bar chart
canvas.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", function(d) {return d.Rhinos;})
.attr("height", 50)
.attr("y", function (d, i) {return i*60})
.attr("fill", "gray");
//Add text to the bars
canvas.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("fill", "black")
.attr("y", function (d, i) {return i*60+25;})
.text(function (d) {return d.Rhinos})
//Add scale
var scale = d3.scaleLinear()
.domain([d3.min(data), d3.max(data)])
.range([0, 1500]);
var g = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function (d, i){
return "translate(0,"+i*height +")";
});
g.append("rect")
.attr("width", function (d) {
return scale(d);
})
.attr("height", height - margin)
g.append("text")
.attr("x", function (d) { return (scale(d)); })
.attr("y", height / 2)
.attr("dy", ".35em")
.text(function (d) { return d; });
})
</script>
</body>
</head>
Run code sni
What is wrong with this code? How to add an axis? The code runs fluently until cell 31. After that I added the scaling and axis. And it doesn’t work. Thank you in advance!