Search code examples
javascriptreactjsnext.jsmui-x-charts

Displaying text on top of bars in MUI X BarChart


I'm using the <BarChart> component from @mui/x-charts (version "^6.19.1") and I want to display the data values on top of each bar for better readability.

Current Output:
enter image description here
Desired Outcome:
enter image description here

Below is my React js code:

const MyData = [
  {
    Name: "All",
    low: 19.63,
    middle: 34.84,
    average: 35.98,
    good: 9.55,
  },
  // ... other data objects
];
export default function({MyData}){
    const lowMarks = [];
    const Basic = [];
    const Proficient = [];
    const Advance = [];
    const xLabels = [];

    MyData.map(({Name, low, middle, average, good })=>{
        lowMarks.push(low)
        middleMarks.push(middle)
        averageMarks.push(average)
        goodMarks.push(good)
        xLabels.push(Name)
    })

return(
<BarChart  xs={12}
  series={
           [
  { data: lowMarks, label: 'low', id: 'low', stack: 'total', color: '#f4cccc',valueFormatter},
  { data: middleMarks, label: 'middle', id: 'middle', stack: 'total', color: '#ffe599', valueFormatter},
  { data: averageMarks, label: 'average', id: 'average', stack: 'total', color: '#b6d7a8', valueFormatter},
 { data: goodMarks, label: 'good', id: 'good', stack: 'total', color: '#9fc5e8', valueFormatter},
 ]
}
yAxis={[{ data: xLabels, scaleType: 'band'}]}
xAxis={[{valueFormatter}]}
layout="horizontal"
tooltip={{ trigger: 'item' }}
>
</BarChart>
)}

Solution

  • Building on top of @Pavan Birari's answer

    You can actually provide a function to the barLabel property in order to format it the way you want. In this case, adding the %

    You can read more on the documentation here: https://mui.com/x/react-charts/bars/#custom-labels

    const Demobar = () => {
      return (
        <BarChart
          ...
          barLabel={(v) => `${v.value}%`}
        />
      )
    }
    

    Which will give a result closer to your intended output

    enter image description here