【问题标题】:unable to display count on the barchart (svg graph)无法在条形图上显示计数(svg 图)
【发布时间】:2021-12-31 20:06:55
【问题描述】:

我目前仅使用 svg、html 和 css 制作堆叠条形图,并且没有使用第三方库。

请参考此codepenhttps://codepen.io/a166617/pen/qBXvzQd

根据堆积条形图,数据正确显示,但不显示每个条形的计数。

此堆叠条形图使用的数据如下

const data = [
    {
      name: 'Transit',
      passed: 2,
      skipped: 5,
      failed: 22,
      untested: 0
    },
    {
      name: 'Access',
      passed: 0,
      skipped: 0,
      failed: 0,
      untested: 100
    }
  ];

根据这些数据,我正在尝试显示计数 2(passed)、5(skipped)、22(failed)和 100(untested

谁能告诉我如何在他们各自的条形图上显示这些计数。为了清楚起见,我想在条形图上显示计数,类似于以下屏幕截图中显示的计数

【问题讨论】:

    标签: javascript html css reactjs svg


    【解决方案1】:

    只需将<text> 元素添加到您的酒吧组。

          return (
            <g key={Math.random()}>
              <rect
                width={50}
                height={`${height}%`}
                fill={bar.color}
                x={60} // multiply with the width (50) + 10 for space
                y={`${y}%`}
              />
              <text
                x={70}                // visible centre point of your bar
                y={`${y + height/2}%`}
                dy="1.3em"            // adjusts the text y position to adjust for
                                      // text descenders. Makes the vertical centring 
                                      // more accurate. Normally 0.3 to -0.35, but has 
                                      // an extra ~1em because of the 180deg rotate.
                textAnchor="middle"   // centre the text horizontall at x
                class="bar-label"     // styling for this text
                >{`${bar.value}%`}</text>
            </g>
          );
    
    .bar-label {
      fill: white;
      font-size: 10px;
      transform-box: fill-box;
      transform: rotateX(180deg);
    }
    

    由于您已将条形 SVG 旋转了 180 度,这一更改有点复杂。这会导致文本颠倒。所以我必须将每个&lt;text&gt; 元素重新竖直翻转。

    【讨论】:

    • LeBeay-感谢您的解决方案。我把条形图复杂化了吗?您是否建议一种更好的方法来显示条形?
    • 进行旋转变换会使添加文本变得有点复杂。但如果你现在快乐,那么你就不需要改变它。但我会通过调整条形段的 Y 坐标来完成“翻转”。此外,我可能不会选择为每个条设置单独的 SVG。我会把它们都放在一个 SVG 中。
    • 我发现很难将所有内容放在一个 svg 下。你能建议怎么做吗
    • 这是一个开始。我还没有完成底部标签,但我认为那里有足够的东西可以让你弄清楚如何做到这一点。 codepen.io/PaulLeBeau/pen/PoKrOgN
    • 谢谢。这很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2018-09-20
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多