reactjsmaterial-uibar-chartmui-x-charts

Simple MUI Barchart displaying number of products sold


I'm trying to make a (what I thought) simple BarChart using @mui/x-charts.

I have the data of products sold, specifically their name and number sold: [{productName, amountSold}, ...]. What I hope the barchart to look like, is something like this:

Desired chart example

I'm not having issues with the styling, but to get the data to display like that. Each product a bar and a label.

I tried a lot of different formats to pass the data to the chart and configuring the labels in the legend, but the closeest I got was only this:

My best attempt

There are two issues with this, though. Obviously, the mismatched colors, but also that it's actually displaying 9 bars, just 6 of them are null, so there is just one of each "category". Meaning the data looks like:

const seriesData = [
  { data: [4550, null, null], label: "Corona" },
  { data: [null, 3775, null], label: "Vodka Bull" },
  { data: [null, null, 3247], label: "Gin Tonic" },
];

How can I properly set the barchar component up, so that each product has a single bar and label in the legend?


Solution

  • The reason you have 9 bars is because you have 3 series and 3 items inside each one. To resolve this, we can update the series array like this, keeping only one value in each data array:

    const seriesData = [ { label: 'Corona', data: [ 4550 ] }, 
    { label: 'Vodka Bull', data: [ 3775 ] }, 
    { label: 'Gin Tonic', data: [ 3247 ] } ]
    

    With this, you should now have one bar for each product, and the legend should be updated and have the correct color codes.

    I also made a small improvement to the behavior when you hover on a bar, since by default it was showing the sales numbers of all products. For this, just add this prop to the <BarChart>:

    tooltip={{ trigger: 'item' }}
    

    This is how it looks with all updates: Bar chart

    Here is my full code, if it helps:

    export default function BarDemo() {
    
      return (
        <Box sx={{ width: '100%' }}>
          <BarChart
            layout="horizontal"
            tooltip={{ trigger: 'item' }}
            height={300}
            series={series}
            yAxis={[{ data: " ", scaleType: 'band', hideTooltip: true }]}
          />
          </Box>
      );
    }
    
    const highlightScope = {
      highlight: 'series',
    } as const;
    
    
    const series = [
      {
        label: 'Corona',
        data: [
          4550
        ],
      },
      {
        label: 'Vodka Bull',
        data: [
          3775
        ],
      },
      {
        label: 'Gin Tonic',
        data: [
          3247
        ],
      },
    ].map((s) => ({ ...s, highlightScope }));