酒吧堆积在一个地方

时间:2019-09-15 21:48:14

标签: javascript d3.js

谁能告诉我如何在一个特定位置堆叠的条形物之间留出空隙? 这是代码: 附注:对不起,我尝试过,但由于某些错误“请添加一些说明”,因此库克没有将其发布为代码段

Part 1

Part 2

Output

2 个答案:

答案 0 :(得分:0)

X scaleBand域被设置为标记值,​​但是您使用i索引对其进行了调用。尝试x(tag[i])

答案 1 :(得分:0)

@ Samrat-将rect附加到svg时,请将代码.attr("x"), function(d,i){return x(i)})中的这一行更改为.attr("x", (d, i) => i * (svgWidth / info.length))。这段代码将整个svg宽度除以数据集的长度,然后将每个值乘以其索引,索引之间的距离就相互分隔。

希望这会有所帮助。

小提琴供您参考:https://jsfiddle.net/zfjcLopw/1/

注意:继续发布关于SO的问题时,请遵循本文列出的指南 https://stackoverflow.com/help/how-to-ask这有助于迅速获得答案

这是更新的代码:

<!DOCTYPE html>

<html>
  <head>
    <title>test</title>
    <script src="https://d3js.org/d3.v5.min.js"></script>
  </head>
  <body>
    <script>
      const width = 600;
      const height = 500;
      const margin = { top: 100, right: 100, bottom: 100, left: 120 };
      const innerWidth = width - margin.left - margin.right;
      const innerHeight = height - margin.top - margin.bottom;
      const barPadding = 2;
      const svg = d3
        .select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height);

      const tag = ["mango", "banana", "apple", "lemon", "coconut"];
      const info = [23, 54, 34, 51, 22];

      const xScale = d3
        .scaleBand()
        .domain(tag.map(d => d))
        .rangeRound([0, innerWidth]);

      const yScale = d3
        .scaleLinear()
        .domain([0, d3.max(info, d => d)])
        .range([innerHeight, 0]);

      const mainG = svg
        .append("g")
        .attr("transform", `translate(${margin.left}, ${margin.top})`);

      const g = mainG
        .selectAll("g")
        .data(info)
        .enter()
        .append("g")
        .attr("transform", `translate(0,0)`);

      g.append("rect")
        .attr("x", (d, i) => i * (innerWidth / info.length))
        // .attr("x", (d, i) => xScale(i)) - This line will stack bars on top of each other
        .attr("y", d => yScale(d))
        .attr("width", innerWidth / info.length - barPadding)
        .attr("height", d => innerHeight - yScale(d))
        .attr("fill", "blue");

      mainG.append("g").call(d3.axisLeft(yScale));
      mainG
        .append("g")
        .call(d3.axisBottom(xScale))
        .attr("transform", `translate(0, ${innerHeight})`);
    </script>
  </body>
</html>