Reputation: 7948
I'm having troubles plotting a simple bar graph. Only a tiny part of the y-axis is showing in my graph:
What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
</style>
<title>My bar chart</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var myData = [{"y":0.31,"x":"Worse","color":"#e41a1c"},{"y":0.36,"x":"Equivalent","color":"#377eb8"},{"y":0.33,"x":"Better","color":"#4daf4a"}] ;
console.log("myData: ", myData);
var height = 400;
var width = 500;
var margin = {left:50,right:50,top:40,bottom:0};
var y = d3.scaleLinear().rangeRound([height, 0]);
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var yAxis = d3.axisLeft(y);
var xAxis = d3.axisBottom(x);
var svg = d3.select("body").append("svg").attr("height","100%").attr("width","100%");
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(myData.map(function(d) { return myData.x; }));
y.domain([0, 1]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(10, "%"))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Probability");
g.selectAll(".bar")
.data(myData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.y); });
</script>
</body>
</html>
Upvotes: 2
Views: 47
Reputation: 102218
For whatever reason, you're setting the width
and height
...
var height = 400;
var width = 500;
...but, when appending the SVG, using percentages...
var svg = d3.select("body")
.append("svg")
.attr("height","100%")
.attr("width","100%");
.. which is strange. So, for this answer, I'll assume that you, indeed, want to use percentages.
The problem here is that, since you didn't define the height of the container (the <body>
), the SVG's height will default to 150px:
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.style("background-color", "red");
console.log("The height is: " + svg.style("height"))
<script src="https://d3js.org/d3.v4.min.js"></script>
One possible solution is setting the height of the body:
html,
body {
height: 100%;
}
Here is the demo:
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.style("background-color", "red");
console.log("The height is: " + svg.style("height"))
html,
body {
height: 100%;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Have in mind that this doesn't guarantee a minimum value at all. For the small snippet window, I'm getting just 220px.
Upvotes: 1