javascript - 轴没有出现在条形图上

标签 javascript d3.js svg

我刚刚开始使用 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/

相关文章:

javascript - 如何加快警报速度,Javascript

javascript - 调整文本大小时如何确保元素保持相同的高度?

javascript - Knockout.js 中的 $.getJSON 错误 URL

javascript - 如何设置 d3 符号的大小?

d3.js:从文件中绘制 map 上两点之间的弧线

jquery - 缩放到一个元素 - jquery SVG

javascript - 使用数组将字符串处理为分隔的单词

javascript - jVectorMap 改变 SVG 描边颜色

javascript - 将 SVG 分享到 Facebook

javascript - 如果矩形低于特定高度,则删除文本 d3js v4