Streamline
Streamline

Reputation: 2122

Is it possible to change pointStyle for elements of a ChartJS bubble chart per dataset?

I have a ChartJS v2 bubble chart with multiple datasets where I want to represent certain data points with different shaped elements.

I've read about point configuration options for pointStyle so the element points can be different shapes, other than circles.

I've tried a few variations and places to add pointStyle but I can't get it working. I only ever see circles.

Is this even possible with a bubble chart? If not is it possible with a scatter chart?

Upvotes: 5

Views: 1726

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31341

If anyone still needs to know this. You can put it in the dataset itself to apply only to that dataset, in options.datasets.bubble to make it apply to all bubble datasets, in options.elements.point to apply it to all point elements or in the root of the options to apply it to the whole chart:

const image = new Image()
image.src = 'https://www.chartjs.org/docs/master/favicon.ico';

const options = {
  type: 'bubble',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
          x: 20,
          y: 30,
          r: 15
        }, {
          x: 40,
          y: 10,
          r: 10
        },
        {
          x: 30,
          y: 22,
          r: 25
        }
      ],
      pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot'),
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)'
    }]
  },
  options: {
    pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot'),
    elements: {
      point: {
        pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot')
      }
    },
    datasets: {
      bubble: {
        pointStyle: (ctx) => (ctx.dataIndex === 2 ? image : 'rectRot')
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
image.onload = () => new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

To the pointStyle you can pass either a canvas element, image or one of the following strings:

  • 'circle'
  • 'cross'
  • 'crossRot'
  • 'dash'
  • 'line'
  • 'rect'
  • 'rectRounded'
  • 'rectRot'
  • 'star'
  • 'triangle'

Upvotes: 1

Related Questions