防止图表溢出保证金?

时间:2019-11-21 17:31:57

标签: recharts

我想显示最近的N个点,但是当将域设置为小于chartData.length的任何值时,图表会向左溢出。

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

enter image description here

  /*
   * 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>
  );

1 个答案:

答案 0 :(得分:1)

根据documentation 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>
  );