Creating a rectangle chart with D3.js

ぃ、小莉子 提交于 2020-01-07 03:41:24

问题


I am trying to make a d3 javascript that creates a rectangle whose color depends on a data set. All of the rectangles are adjacent to each other like:

         [][][][][][]
         [][][][][][]

I got my script to work to create rectangles for all of my data, but it overflows like:

          [][][][][][][][][][][][][][][][][][][][][][][][][][][]

How can I create width and height properties for my d3 script so it looks more like

        [][][][]
        [][][][]
        [][][][]

Here is my script:

    <script>
         //for whatever data set
         var data = [];
         //Make an SVG Container
     var svgContainer = d3.select("body").selectAll("svg")
                                 .data(data)
                                 .enter().append("svg")
                                 .attr("width", 38)
                                 .attr("height", 25);

    //Draw the rectangle
   var rectangle = svgContainer.append("rect")
                     .attr("x", 0)
                     .attr("y", 5)
                     .attr("width", 38)
                     .attr("height", 25);
    </script>

回答1:


You have to change the x and y properties.

.attr("x", function(d, i) {
    return 5 + (i%itemPerLine) * widthRect;
})
.attr("y", function(d, i) {
    return 5 + Math.floor(i/itemPerLine) * heightRect;
})

(itemPerLine is the number of rect per line)

See this fiddle as example



来源:https://stackoverflow.com/questions/39583209/creating-a-rectangle-chart-with-d3-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!