Search code examples
chartsscatter

Chart.js specific label next to point


I'm trying to get chartjs to show a specific label next to each point, for example in this script it should display "TRALALA" in the label as well as mouse hover, but instead it shows the coordinates. How to have the specific label instead ?

https://jsfiddle.net/z0eLygwx/

thanks

var valuedata = [{
  x: 3,
  y: 5
}];
var valuelabel = ['TRALALA'];

var chartData = {
  labels: valuelabel,
  datasets: [{
    label: 'Distance',
    borderColor: '#2196f3', // Add custom color border            
    backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
    data: valuedata,
    pointRadius: 10,
    pointHoverRadius: 12
  }]
};


var myBarChart = new Chart(document.getElementById("myChart1"), {
  type: 'scatter',
  data: {
    labels: valuelabel,
    datasets: [{
      label: 'Distance',
      borderColor: '#2196f3', // Add custom color border            
      backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
      data: valuedata,
      pointRadius: 10,
      pointHoverRadius: 12
    }]
  },
  options: {
    legend: {
      display: true
    },
    title: {
      display: true,
      text: 'Distance of JDPT kanji compared to the equivalent JLPT level'
    },
    scales: {
      yAxes: [{
        type: 'logarithmic',
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Count',
          fontSize: 16
        }
      }],
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Distance',
          fontSize: 16
        },
        gridLines: {
          display: true
        }
      }]
    },
    plugins: {
      datalabels: {
        color: '#d6621e',
        align: 'right',
        offset: 16,
        font: {
          weight: 'bold'
        }
      }
    }
  }

});


myBarChart.update();

Solution

  • Ok I got it with

    formatter: function(value, context) {
    context.chart.data.labels[context.dataIndex];
    }
    

    For example

    var myBarChart = new Chart(document.getElementById("bar-chart"), {
      type: 'line',
      data: {
        labels: ['a', 'b'],
        datasets: [{
          data: [10, 20]
        }]
      },
      options: {
        plugins: {
          datalabels: {
            formatter: function(value, context) {
              return context.chart.data.labels[context.dataIndex];
            }
          }
        }
      }
    });