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

如何用Recharts实现X轴按月显示唯一标签的折线图?

Fix Duplicate Month Labels on Recharts X-Axis for Daily Data

Got it, let's fix that duplicate month label issue on your Recharts line chart! The problem right now is your formatXAxis function converts every daily date to a month name—so you end up with the same month repeated dozens of times. Here's how to make each month show up only once, just like the clean Google CRM stock chart you're referencing.

The Solution: Track Previous Month with a Closure

We'll modify the formatXAxis function to remember the last month we displayed. Only when the current date's month is different from the last one will we render the month label; otherwise, we return an empty string to hide the duplicate.

Here's the updated code:

// Use a closure to track the previously displayed month
const formatXAxis = (() => {
  let prevMonth = null;
  return (tickItem) => {
    const d = new Date(tickItem);
    const currentMonth = d.toLocaleString('default', { month: 'long' });
    
    // Only return the month name if it's different from the last one
    if (currentMonth !== prevMonth) {
      prevMonth = currentMonth;
      return currentMonth;
    }
    return '';
  };
})();

const SimpleLineChart = React.createClass({
  render () {
    return (
      <LineChart width={800} height={400} data={data} margin={{top: 5, right: 30, left: 20, bottom: 5}}>
        <XAxis tickFormatter={formatXAxis} dataKey="name"/>
        <YAxis/>
        <CartesianGrid strokeDasharray="3 3"/>
        <Tooltip/>
        <Legend />
        <Line type="monotone" dataKey="uv" stroke="#8884d8" activeDot={{r: 8}}/>
      </LineChart>
    );
  }
})

ReactDOM.render( <SimpleLineChart />, document.getElementById('container') );

How This Works

  • The self-invoking function creates a closure that holds the prevMonth variable, which persists between calls to formatXAxis.
  • For each tick item (daily date), we get the current month name.
  • If it's a new month (different from prevMonth), we update prevMonth and return the month name to display it.
  • If it's the same as the last month, we return an empty string, so no duplicate label is rendered.

Quick Notes

  • Make sure your data is sorted by date: This logic relies on dates being in chronological order. If your data isn't sorted, sort it first before passing it to the LineChart.
  • Adjusting label position: If you want the month label to sit centered under the entire month's data instead of at the first day, you'd need to use a custom XAxis component or calculate tick positions manually. But the above code solves the core duplicate label issue!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:17:29