<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8"/>
<title>D3 Bar chart</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h1>Bar Chart</h1>
<script>
//D3 Code
var w = 500;
var h = 100;
var dataset = [14, 5, 26, 23, 9];
var barPadding = 45;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length - barPadding);
})
.attr("y", 0)
.attr("width", 50)
.attr("height", 100);
</script>
</body>
</html>
当我运行我的代码时,我得到一个条形图,但每个条形图都是相同的,所以它只是一个具有相同值的图表,但我的代码中的数据集是不同的值。如何更改我的代码以便生成合适的条形图?
答案 0 :(得分:0)
您需要设置height
。您可以传递类似
.attr("height", dataValue => dataValue);
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8"/>
<title>D3 Bar chart</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h1>Bar Chart</h1>
<script>
//D3 Code
var w = 500;
var h = 100;
var dataset = [14, 5, 26, 23, 9];
var barPadding = 45;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length - barPadding);
})
.attr("y", 0)
.attr("width", 50)
.attr("height", dataValue => dataValue);
</script>
</body>
</html>