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

如何在React中使用Recharts创建可横向滚动且Y轴固定的面积图

Recharts面积图横向滚动Y轴固定解决方案

问题原因

挤压变形是因为固定了图表宽度,数据量上升后X轴每个刻度分配到的宽度被压缩导致的,以下是两种可直接落地的实现思路:


方案1:CSS滚动+Y轴粘性定位(最符合横向滚动交互需求)

实现步骤:

  • 外层包裹固定宽度、带横向滚动的容器,限制可视区域大小
  • 图表宽度根据数据量动态计算,保证每个X轴刻度有足够展示宽度,不会被挤压
  • 给Y轴元素加粘性定位固定在左侧,滚动时不跟随移动

修改后代码示例:

// 外层容器加样式,未使用styled-components可以换成行内样式+全局CSS实现
const ChartWrapper = styled.div`
  width: 730px;
  overflow-x: auto;
  overflow-y: hidden;
  .recharts-yAxis {
    position: sticky;
    left: 0;
    z-index: 10;
    background: #fff;
  }
`

const YourComponent = () => {
  const [arr, setArr] = React.useState([])
  const timeoutRef = React.useRef(null)
  const time = new Date().toLocaleString()

  const validate = React.useCallback(() => {
    setArr((prevState) =>
      [...prevState, { X: Math.random() >= 0.5 ? 5 : 0 }]
    );
  }, []);

  React.useEffect(() => {
    if (timeoutRef.current !== null) {
      clearTimeout(timeoutRef.current);
    }
    const interval = 6000;
    const speed = 1000;
    for (let i = 0; i < interval; i++) {
      timeoutRef.current = setTimeout(() => {
        timeoutRef.current = null;
        validate();
      }, i * speed);
    }
    return () => clearTimeout(timeoutRef.current)
  }, [validate]);

  // 动态计算图表宽度,每个X轴项占30px,加上左右边距总和
  const chartWidth = arr.length * 30 + 50

  return (
    <div>
      <h1>{time}</h1>
      <ChartWrapper>
        <AreaChart
          width={chartWidth}
          height={250}
          data={arr}
          margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
        >
          <YAxis />
          <XAxis additive='sum' />
          <Tooltip />
          <Legend />
          <Area
            type='monotone'
            dataKey='X'
            stroke='#8884d8'
            isAnimationActive={false}
            additive='sum'
          />
          <Brush startIndex={0} endIndex={10}>
            <AreaChart>
              <Area dataKey='X' isAnimationActive={false} />
            </AreaChart>
          </Brush>
        </AreaChart>
      </ChartWrapper>
    </div>
  );
}

方案2:用Brush组件控制可视区间(适合超大数据量,性能更高)

你当前代码已经引入了Brush组件,只要把Brush的startIndex、endIndex和X轴的domain绑定,每次只渲染选中区间的10-20条数据,图表宽度固定730也不会出现挤压,不需要额外写滚动逻辑,交互更简洁。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:48:03