我刚刚开始使用 D3 和 JS,我正在尝试向条形图添加 X 轴。它没有出现。我认为这是因为我代码底部的 svg.append("g")
不正确(没有变量 g)。那里应该有什么变量?
条形图.js
// Create data array of values to visualize
var dataArray = [23, 13, 21, 14, 37, 15, 18, 34, 30];
// Create variable for the SVG
var svg = d3.select("body").append("svg")
.attr("height","100%")
.attr("width","100%");
// Select, append to SVG, and add attributes to rectangles for bar chart
svg.selectAll("rect")
.data(dataArray)
.enter().append("rect")
.attr("class", "bar")
.attr("height", function(d, i) {return (d * 10)})
.attr("width","40")
.attr("x", function(d, i) {return (i * 60) + 25})
.attr("y", function(d, i) {return 400 - (d * 10)});
// Select, append to SVG, and add attributes to text
svg.selectAll("text")
.data(dataArray)
.enter().append("text")
.text(function(d) {return d})
.attr("class", "text")
.attr("x", function(d, i) {return (i * 60) + 36})
.attr("y", function(d, i) {return 415 - (d * 10)});
//add axis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
最佳答案
“g”不是变量,它是 SVG 中的组 ( <g>
) 元素。
这里的问题似乎是这一行:
.attr("transform", "translate(0," + height + ")")
如果height
是 SVG 的高度,不会显示任何内容,因为您正在将轴平移到 SVG 的末尾。
因此,解决方案是将其转换为小于该值的值:
.attr("transform", "translate(0," + (height - padding) + ")")
关于javascript - 轴没有出现在条形图上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478009/