无法在条形图(svg 图形)上显示计数

unable to display count on the barchart (svg graph)

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

请参考这篇codepen https://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)

谁能告诉我如何在各自的条形图上显示这些计数。明确地说,我想在条形图上显示类似于下面屏幕截图中显示的计数

只需将 <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 度,因此此更改有点复杂。这导致文本颠倒。所以我必须将每个 <text> 元素垂直翻转回来。