5

I am trying to replace points of a scatter plot with a PNG image. Based on the documentation, the pointStyle accepts either a string or an image. However instead of the image on the first point, it just shows a regular scatter plot point. Any ideas?

var ctx = document.getElementById("myChart").getContext('2d');
var img = new Image();
var img1 = img.src = 'assets/img/small/STORM.png';
var imageData = {
  datasets: [{
    pointStyle: [img1, 'rect', 'triangle', 'circle'],
    data: [{
      x: 1.447377,
      y: -0.014573
    }, {
      x: 2.365398,
      y: -1.062847
    }, {
      x: -2.507778,
      y: 0.389309
    }, {
      x: -0.432636,
      y: 0.124841
    }]
  }]
}

var myChart = new Chart(ctx, {
  type: 'scatter',
  data: imageData,
  options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

You can see a working example in jsfiddle here

Tasos
  • 7,325
  • 18
  • 83
  • 176

1 Answers1

1

According to Chart.js documentation, pointStyle is either a string or an Image but not an array.

If you want to have individual styles for your points, you can use the Plugin Core API. It offers several hooks that may be used for executing custom code. You could use the afterDraw hook to assign a different pointStyle to each point.

plugins: {
  afterUpdate: function(chart) {
    const meta = chart.getDatasetMeta(0);
    meta.data[0]._model.pointStyle = img;
    meta.data[1]._model.pointStyle = 'rect';
    meta.data[2]._model.pointStyle = 'triangle';
    meta.data[3]._model.pointStyle = 'circle';
  }
},

I your amended code below, I used a slightly different but more compact approach and defined the pointStyles array outside of the chart configuration.

const img = new Image();
img.src = 'https://i.stack.imgur.com/gXQrT.png';
const pointStyles = [img, 'rect', 'triangle', 'circle'];

new Chart(document.getElementById('myChart'), {
  type: 'scatter',
  plugins: {
    afterUpdate: chart => {
      chart.getDatasetMeta(0).data.forEach((d, i) => d._model.pointStyle = pointStyles[i]);
    }
  },
  data: {
    datasets: [{
      data: [
        {x: 1.447377, y: -0.014573},
        {x: 2.365398, y: -1.062847}, 
        {x: -2.507778, y: 0.389309},
        {x: -0.432636, y: 0.124841}
      ],
      backgroundColor: ['white', 'green', 'red', 'orange'],
      pointRadius: 10
    }]
  },
  options: {
    legend: {
      display: false
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72