javascriptcssreactjsnext.jsrecharts

Recharts tick on y axis doesn't align with CartesianGrid


As you can see in the 1st picture, the text "16L" doesn't vertically align with the line of CartesianGrid. I try using syncWithTicks={true} but doesn't work. Is it possible to adjust the position of the topmost tick so that it aligns?

'use client'

import React from "react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  XAxis,
  YAxis,
} from "recharts";

export const InnerBarChart = () => {
  const formattedWaterUsage = [
    {
      date: "00:00",
      startTs: 1751958000000,
      endTs: 1751961599000,
      volume: 12.337,
    },
    {
      date: "01:00",
      startTs: 1751961600000,
      endTs: 1751965199000,
      volume: 14.179,
    },
    {
      date: "02:00",
      startTs: 1751965200000,
      endTs: 1751968799000,
      volume: 11.665,
    },
    {
      date: "03:00",
      startTs: 1751968800000,
      endTs: 1751972399000,
      volume: 13.541,
    },
  ];

  return (
    <ResponsiveContainer width={"100%"} height={600}>
      <BarChart
        width={877}
        height={409}
        data={formattedWaterUsage}
        margin={{
          top: 0,
          right: 50,
          left: 50,
          bottom: 0,
        }}
        {...{
          overflow: "visible",
        }}
      >
        <CartesianGrid stroke="#ccc" vertical={false} syncWithTicks={true} />
        <XAxis
          dataKey="date"
          tickLine={false}
          axisLine={false}
        />
        <YAxis
          type="number"
          dx={-10}
          axisLine={false}
          tickLine={false}
          tick={{ fontSize: 18 }}
          tickFormatter={(value) => {
            return `${value} L`;
          }}
        />
        <Bar dataKey="volume" fill="#51A9FE" />
      </BarChart>
    </ResponsiveContainer>
  );
};

Actual Result enter image description here

Expected Result enter image description here


Solution

  • The issue is because Recharts doesn't rescale the chart dynamically, and sometime the tick positions are not aligned with CartesianGrid lines, even when using syncWithTicks={true}.

    Simple Solution: Add interval={0} to your YAxis Component.

    <YAxis
      type="number"
      dx={-10}
      axisLine={false}
      tickLine={false}
      tick={{ fontSize: 18 }}
      interval={0}  // Add this line
      tickFormatter={(value) => {
        return `${value} L`;
      }}
    />
    

    The interval={0} prop forces the YAxis to show all calculated ticks, which ensures proper alignment with the CartesianGrid horizontal lines.