Skip to content Skip to sidebar Skip to footer

Bars Getting Stacked At One Place

Can anyone tell me how to provide gaps between the bars that are getting stacked at one particular place? Here is the code: P.s: Sorry i tried but coukd not post it as a code snipp

Solution 1:

@Samrat- When appending rect to your svg, change this line in your code .attr("x"), function(d,i){return x(i)}) to .attr("x", (d, i) => i * (svgWidth / info.length)). This code divides the entire svg width by the length of your dataset and multiplies each value by its index, which distances bars from each other.

Hope this helps.

Fiddle for your reference: https://jsfiddle.net/zfjcLopw/1/

Note: Going forward while posting questions on SO, follow the guidelines listed in this articlehttps://stackoverflow.com/help/how-to-ask. This helps in getting answers promptly.

Here is the updated code:

<!DOCTYPE html><html><head><title>test</title><scriptsrc="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>

Solution 2:

X scaleBand domain is set to tag values, but you call it with i index. Try x(tag[i])

Post a Comment for "Bars Getting Stacked At One Place"