首页 > 解决方案 > 防止rechart溢出到保证金?

问题描述

我想显示最近的 N 点,但是当将域设置为小于chartData.length.

我看到我可以通过添加margin={{left:59}}to将所有内容都向左移动<ComposedChart>,但这似乎有点 hacky。有没有更好的方法来隐藏这条溢出的线?

在此处输入图像描述

  /*
   * NOTE: the axis `domain` requires a _function_ if you want to display less than the total number of
   * data points (see: https://stackoverflow.com/questions/53751564/can-i-set-the-recharts-axis-domain-max-lower-than-datamax)
   */
  const pointsToDisplay = 8;
  const xAxisStart = chartData.length - pointsToDisplay;
  return (
    <ResponsiveContainer height={210}>
      <ComposedChart data={chartData}>
        <XAxis dataKey="index" tick={true} type="number" domain={[() => xAxisStart, 'dataMax']} />
        <YAxis tick={false} domain={['dataMin - 3', 'dataMax + 3']} />
        <Line type="monotone" dataKey="score" strokeWidth={5} dot={false} stroke="var(--accentColor)" />
      </ComposedChart>
    </ResponsiveContainer>
  );

标签: recharts

解决方案


根据文档 allowDataOverflow必须设置为 true 才能裁剪数据。然后,您还可以从域数组中删除该函数并简单地使用该变量:

/*
   * NOTE: the axis `domain` requires a _function_ if you want to display less than the total number of
   * data points (see: https://stackoverflow.com/questions/53751564/can-i-set-the-recharts-axis-domain-max-lower-than-datamax)
   */
  const pointsToDisplay = 8;
  const xAxisStart = chartData.length - pointsToDisplay;
  return (
    <ResponsiveContainer height={210}>
      <ComposedChart data={chartData}>
        <XAxis dataKey="index" tick={true} type="number" domain={[xAxisStart, 'dataMax']} allowDataOverflow={true}/>
        <YAxis tick={false} domain={['dataMin - 3', 'dataMax + 3']} />
        <Line type="monotone" dataKey="score" strokeWidth={5} dot={false} stroke="var(--accentColor)" />
      </ComposedChart>
    </ResponsiveContainer>
  );

推荐阅读