user5323957
user5323957

Reputation: 552

Created A Bar Chart But Height Is Not Reciprocating Changes

Hello Created A Bar Char Using D3 Using Below Code

var dataset = [5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25];
var w = 500;
var h = 100;
var barpadding = 1;
var svg = d3.select("body")
            .append("svg")
            .attr("width", w)
            .attr("height", h);
var rect = svg.selectAll("rect")
              .data(dataset)
              .enter()
              .append("rect")
              .attr("x", function (d, i) {
                  return i * (w / dataset.length)
              })
              .attr("y", function (d) {
                  return (h - d);
              })
              .attr("height", function (d) {
                  return (d *2)
              })
              .attr("width", w / dataset.length - barpadding)
              .attr("fill", function (d) {
                  return "rgb(0, 0, " + (d * 10) + ")";
              });
              
    <div  class="bar"></div>
   

As You Can See At Starting My Height Attribute Is Like

 .attr("height", function (d) {
                  return (d *2)
              })

And Corresponding Image Is enter image description here

Now I Have Changed It To 5 Times Like

  .attr("height", function (d) {
                  return (d *5)
              })

But Can'tenter image description here See Any Changes In My Bar's Height Any Help ??

fiddle link

Upvotes: 0

Views: 29

Answers (1)

Gregory Ling
Gregory Ling

Reputation: 195

You need to multiply the 'd' variable in the 'y' attribute change as well as the height. So the 'y' function ends up as:

.attr("y", function (d) {
     return (h - (d * 5));
})

If you took out the subtracting from 'h' in the 'y' attribute and just left the 'y' attribute with no change, you see that your graph's height does change. The y attribute function is regulating the position of each rectangle so that the extended portion from multiplying it by 2 or 5 is hidden below the graph.

Upvotes: 1

Related Questions