我在制作一个简单的条形图时遇到了麻烦。在我的图表中只显示y轴的一小部分:
我做错了什么?
<!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>
答案 0 :(得分:1)
无论出于何种原因,您都要设置width
和height
...
var height = 400;
var width = 500;
...但是,在附加SVG时,使用百分比...
var svg = d3.select("body")
.append("svg")
.attr("height","100%")
.attr("width","100%");
..这很奇怪。所以,对于这个答案,我会假设你确实想要使用百分比。
这里的问题是,由于你没有定义容器的高度(<body>
),SVG的高度默认为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>
一种可能的解决方案是设置身体的高度:
html,
body {
height: 100%;
}
以下是演示:
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>
请注意,根本不保证最低价值。对于小片段窗口,我只得到220px。