Search code examples
reactjsd3.jschartsmui-xmui-x-charts

In MUI X Charts, how to prevent LineChart Y axis label from overlapping with ticks labels?


I have been using very basic LineChart that renders like this:

LineChart with yAxis label overlap

As you can see, the Money label is overlapping with the ticks. What is the best way of avoiding this?

Source of the LineChart:


  const xAxisMax = _.max(turns) ?? defaultXAxisMax
  const yAxisMax = _.max(money) ?? defaultYAxisMax
  return (
    <LineChart
      xAxis={[
        {
          data: turns,
          min: 1,
          max: xAxisMax,
          label: 'Turns',
          scaleType: 'linear',
        },
      ]}
      yAxis={[
        {
          min: 0,
          max: yAxisMax,
          label: 'Money',
          scaleType: 'linear',
          //labelStyle: { ??? },
        },
      ]}
      series={[
        {
          data: money,
        },
      ]}
      width={500}
      height={300}
    />
  )
}

Relevant lines from my npm ls

+-- @emotion/[email protected]
+-- @emotion/[email protected]
+-- @fontsource/[email protected]
+-- @mui/[email protected]
+-- @mui/[email protected]
+-- @mui/[email protected]
+-- @vitejs/[email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]

In the docs, I found some mentions of example customizations here:

https://mui.com/x/react-charts/axis/#text-customization

which says:

<ScatterChart
  {/** ... */}
  bottomAxis={{
    labelStyle: {
      fontSize: 14,
      transform: `translateY(${
            // Hack that should be added in the lib latter.
            5 * Math.abs(Math.sin((Math.PI * props.angle) / 180))
          }px)`
    },
    tickLabelStyle: {
      angle: 45,
      textAnchor: 'start',
      fontSize: 12,
    },
  }}

This plus few other relevant articles make me believe I could somehow apply the labelStyle of yAxis. However, whatever I try, padding, margin, and so on, it always appears to be overridden/ignored by the rendered page, as inspected by Chrome DevTools.

However, transform appears to be actually rendered, e.g.:

labelStyle: { transform: 'rotate(-90deg)' },

but I do not know what is the correct value of transform to just shift the label a little bit more to the side.

Note I do not have any css customizations anywhere impacting any kind of layout. No custom layout in <ThemeProvider> and no other shenanigans.


Solution

  • Here is the CSS solution for it, we can just add a class to the chart, to prevent the CSS affecting other charts!

    MuiChartsYAxis-directionY docs

    .custom-y-padding-bottom .MuiChartsAxis-directionY .MuiChartsAxis-label {
      transform: translateX(-10px) !important;
    }
    

    stackblitz