You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Victory Stack垂直堆叠中排序数据,使最大Y值位于底部?

解决垂直条形图Y轴最大值在底部的问题

要实现Y轴最大值处于底部的效果,别用VictoryBar的sortKey/sortOrder——这俩是用来排序水平方向X轴数据的,直接反转Y轴的定义域方向就能搞定,结合你的堆叠图表场景,具体修改如下:

核心思路

Victory默认Y轴是从下到上数值递增,我们通过给VictoryChart设置domain={{ y: [maxY, 0] }},把Y轴的最大值设为定义域下限、最小值设为上限,就能让最大值显示在底部,堆叠的条形也会自动适配这个反转的轴。

修改后的代码

class App extends React.Component {
  render() {
    const getBarData = () => {
      return [1, 2,3,4].map((k) => {
        return [
          { x: 1, y: k*20 },
          { x: 2, y: k*30 },
          { x: 3, y: k*10 },
        ];
      });
    };

    // 动态计算Y轴最大值,避免硬编码
    const maxY = Math.max(...getBarData().flat().map(item => item.y));

    return (
      <div>
        <VictoryChart 
          domainPadding={{ x: 50 }} 
          width={400} 
          height={400}
          // 反转Y轴定义域
          domain={{ y: [maxY, 0] }}
        >
            <VictoryGroup offset={20} style={{ data: { width: 15 } }}>
              <VictoryStack colorScale="red">
                {getBarData().map((data, index) => {
                  return <VictoryBar key={index} data={data}/>;
                })}
              </VictoryStack>
              <VictoryStack colorScale="green">
                {getBarData().map((data, index) => {
                  return <VictoryBar key={index} data={data}/>;
                })}
              </VictoryStack>
              <VictoryStack colorScale="blue">
                {getBarData().map((data, index) => {
                  return <VictoryBar key={index} data={data}/>;
                })}
              </VictoryStack>
            </VictoryGroup>
          </VictoryChart>
      </div>
    );
  }
}

ReactDOM.render(<App/>, mountNode);

原图表效果

原垂直条形图效果

修改后,Y轴最大值会显示在底部,堆叠的条形也会从底部(最大值)开始向上堆叠到最小值。

内容的提问来源于stack exchange,提问作者Dholariya Dharmik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:25:33