酒吧堆积在一个地方 [英] Bars getting stacked at one place

查看:237
本文介绍了酒吧堆积在一个地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何在一个特定位置堆叠的条形物之间留出空隙?
这是代码:
附:抱歉,我尝试过,但是由于某些错误请添加一些解释,coukd并未将其发布为代码段。

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 snippet due to some error "Please add some explanation"

第1部分

第2部分

输出

推荐答案

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

@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.

希望这会有所帮助。

提琴供您参考: 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>

这篇关于酒吧堆积在一个地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆