Recharts堆叠柱状图问题:消除柱间空白及条件设置圆角
Hey there! Let's fix those two Recharts stacked bar issues for you:
1. Eliminating the Gap Between Stacked Bars
The blank space between your stacked bars is likely caused by the default barGap value (which controls spacing between bars in the same stack). You were using barCategoryGap, but that's for spacing between different categories on the x-axis, not within a single stack.
To fix this, add barGap={0} to each of your <Bar> components (or set it on the parent <BarChart> component to apply it globally):
<Bar dataKey="savedGain" stackId="a" fill="url(#colorUv_blue)" name="Secured gain with AB Tasty" stroke={false} barSize={20} radius={[25, 25, 0, 0]} strokeWidth={4} barGap={0} // Removes internal stack gap /> <Bar dataKey="gain" stackId="a" fill="url(#colorUv_turquoise)" name="Uplift with AB Tasty" stroke={false} barSize={20} strokeWidth={4} radius={[25, 25, 0, 0]} barGap={0} // Add this to the second bar too />
2. Conditional Rounded Corners When <Cell> Doesn't Support radius
You're right—Recharts' <Cell> component doesn't have a built-in radius prop. Instead, we can use a custom shape for the Cell to control rounded corners based on your conditions. Here's how:
Step 1: Create a Custom Cell Shape
Define a reusable SVG path component that applies rounded corners only when your condition is met. This gives you fine-grained control over individual corners:
const ConditionalRoundedCell = (props) => { const { x, y, width, height, fill, payload } = props; // Replace this with your actual condition (e.g., based on payload values) const shouldApplyRoundedCorners = payload.gain > 0; // Adjust radius values to match your needs [top-left, top-right, bottom-right, bottom-left] const [tl, tr, br, bl] = shouldApplyRoundedCorners ? [25, 25, 0, 0] : [0, 0, 0, 0]; return ( <path d={`M${x + tl},${y} L${x + width - tr},${y} Q${x + width},${y} ${x + width},${y + tr} L${x + width},${y + height - br} Q${x + width},${y + height} ${x + width - br},${y + height} L${x + bl},${y + height} Q${x},${y + height} ${x},${y + height - bl} L${x},${y + tl} Q${x},${y} ${x + tl},${y}Z`} fill={fill} stroke="none" /> ); };
Step 2: Use the Custom Shape in Your Cells
Replace your static <Bar> components with dynamic ones that render <Cell> using the custom shape:
<Bar dataKey="savedGain" stackId="a" barSize={20} barGap={0}> {yourDataArray.map((entry, index) => ( <Cell key={`saved-gain-${index}`} fill="url(#colorUv_blue)" shape={ConditionalRoundedCell} /> ))} </Bar> <Bar dataKey="gain" stackId="a" barSize={20} barGap={0}> {yourDataArray.map((entry, index) => ( <Cell key={`gain-${index}`} fill="url(#colorUv_turquoise)" shape={ConditionalRoundedCell} /> ))} </Bar>
Just update shouldApplyRoundedCorners to check whatever condition you need (e.g., based on entry.savedGain, entry.gain, or other data properties).
内容的提问来源于stack exchange,提问作者jibeeeee

