[Chartjs]-Change size of bubble radius without changing r value

2👍

This can be done with the Plugin Core API. The API offers different hooks that may be used for executing custom code. In your case, you could use the afterDatasetUpdate hook to increase the radius of the points in the dataset’s metadata.

plugins:[{
  afterDatasetUpdate: chart => {
    chart.getDatasetMeta(0).data.forEach(v => {
      v._model.radius *= 10;
      v._options.hoverRadius = v._model.radius;
    })
  }
}],
new Chart('canvas', {
  type: 'bubble',
  plugins: [{
    afterDatasetUpdate: chart => {
      chart.getDatasetMeta(0).data.forEach(v => {
        v._model.radius *= 10;
        v._options.hoverRadius = v._model.radius;
      })
    }
  }],
  data: {
    datasets: [{
      label: 'First Dataset',
      data: [
        {x: 10, y: 20, r: 1 }, 
        {x: 20, y: 10, r: 2 }
      ],
      backgroundColor: 'rgb(255, 99, 132)'
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          min: 5,
          max: 25
        }
      }],
      yAxes: [{
        ticks: {
          min: 5,
          max: 25
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="90"></canvas>

0👍

For developers using version 3.9.1 it is like this:

const pixelValue = (scale, v) => {
  const val = scale.getValueForPixel(v)
  return Math.trunc(isNaN(val) ? v * 6 : 3)
}

const $chart = document.getElementById("chart");
const chart = new Chart($chart, {
  type: "bubble",
  data: {
    datasets: [{
      label: "scaled radius",
      backgroundColor: 'rgb(255, 99, 132)',
      data: [{
          x: 10,
          y: 11,
          size: 1
        },
        {
          x: 20,
          y: 5,
          size: 3
        }
      ],
      radius: context => {
        const scale = context.chart.scales.y
        const size = context.dataset.data[context.dataIndex].size
        const value = Math.abs(pixelValue(scale, size))

        return value
      },
    }]
  },
  options: {
    maintainAspectRatio: false,
    scales: {
      x: {
        min: 0,
        max: 30
      },
      y: {
        min: 2,
        max: 14
      }
    }
  }
})
.wrapper {
  max-width: 800px;
  max-height: 180px;
}

canvas {
  user-select: none;
}
<div class="wrapper" style="height: 180px; width: 600px">
  <canvas id="chart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Leave a comment