Search code examples
javascriptreactjschart.jsbubble-chartreact-chartjs

How to change default label of each bubble in bubble chart using chartjs-plugin-datalabels


I am trying to add labels to each bubble in the bubble chart using chartjs-plugin-datalabels. For each bubble, I want to show the label property of each object of data.dataset array
like "Grapefruit", "Lime". I am getting the value of r for all bubbles. Can we change this label?

I saw examples but did not get them right. I don't know what I'm doing wrong.

const data = {
  datasets: [
    {
      label: 'Grapefruit',
      data: [
        {
          x: 10,
          y: 40,
          r: 40,
        },
      ],
      backgroundColor: 'rgb(255, 99, 132)',
    },

    {
      label: 'Lime',

      data: [
        {
          x: 23,
          y: 37,
          r: 40,
        },
      ],
      backgroundColor: 'rgb(105, 89, 175)',
    },
    {
      label: 'Coconut',
      data: [
        {
          x: 26,
          y: 33,
          r: 40,
        },
      ],
      backgroundColor: 'rgb(249, 236, 61)',
    },
    {
      label: 'Mango',
      data: [
        {
          x: 40,
          y: 40,
          r: 40,
        },
      ],
      backgroundColor: 'rgb(255, 128, 0)',
    },
  ],
};

const options = {
  scales: { x: { display: false }, y: { display: false } },
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false,
    },
    datalabels: {},
  },
};

const App = () => {
  return <Bubble data={data} height={415} width={310} options={options} />;
};

Solution

  • You can use the formatter function in the datalabels plugin to achieve this:

    Chart.register(ChartDataLabels)
    
    const options = {
      type: 'bubble',
      data: {
        datasets: [{
            label: 'Orange',
            data: [{
              x: 1,
              y: 4,
              r: 26,
              fruit: 'orange'
            }],
            backgroundColor: 'orange'
          },
          {
            label: 'Apple',
            data: [{
              x: 4,
              y: 2,
              r: 26,
              fruit: 'apple'
            }],
            backgroundColor: 'red'
          },
          {
            label: 'Grape',
            data: [{
              x: 6,
              y: 1,
              r: 26
            }],
            backgroundColor: 'purple'
          }
        ]
      },
      options: {
        plugins: {
          datalabels: {
            color: 'white',
            formatter: (dp, ctx, b) => (ctx.dataset.label)
          }
        }
      }
    }
    
    const ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2 "></script>
    </body>