I am currently working on a stacked barchart using only svg, html and css and no third party library is used for this.
CodePudding user response:
Just add a <text>
element into your bar group.
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);
}
This change is complicated a little by the fact that you've rotated your bar SVGs by 180deg. That causes the text to be upside down. So I have to flip each <text>
element back upright.