Bubbles in a chartjs bubble chart with labels - Javascript Chart.js

Javascript examples for Chart.js:Bubble Chart

Description

Bubbles in a chartjs bubble chart with labels

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJs Bubble Title on bubbles</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//  w w w  .ja v a2 s . c o  m
new Chart(document.getElementById("bubble-chart"), {
  type: 'bubble',
  data: {
    labels: "Africa",
    datasets: [{
      label: ["China"],
      backgroundColor: "rgba(255,221,50,0.2)",
      borderColor: "rgba(255,221,50,1)",
      title: "dataTitle1",
      data: [{
        x: 21269017,
        y: 5.245,
        r: 15
      }]
    }, {
      label: ["Denmark"],
      backgroundColor: "rgba(60,186,159,0.2)",
      borderColor: "rgba(60,186,159,1)",
      title: "dataTitle2",
      data: [{
        x: 258702,
        y: 7.526,
        r: 10
      }]
    }, {
      label: ["Germany"],
      backgroundColor: "rgba(0,0,0,0.2)",
      borderColor: "#000",
      title: "dataTitle3",
      data: [{
        x: 3979083,
        y: 6.994,
        r: 15
      }]
    }, {
      label: ["Japan"],
      backgroundColor: "rgba(193,46,12,0.2)",
      borderColor: "rgba(193,46,12,1)",
      title: "dataTitle4",
      data: [{
        x: 4931877,
        y: 5.921,
        r: 15
      }]
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Predicted world population (millions) in 2050'
    },
    scales: {
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: "Happiness"
        }
      }],
      xAxes: [{
        scaleLabel: {
          display: true,
          labelString: "GDP (PPP)"
        }
      }]
    }
  }
});
Chart.plugins.register({
  afterDatasetsDraw: function(chart, easing) {
    var ctx = chart.ctx;
    chart.data.datasets.forEach(function(dataset, i) {
      var meta = chart.getDatasetMeta(i);
      if (meta.type == "bubble") { //exclude scatter
        meta.data.forEach(function(element, index) {
          ctx.fillStyle = 'rgb(0, 0, 0)';
          var fontSize = 13;
          var fontStyle = 'normal';
          var fontFamily = 'Helvetica Neue';
          ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
          var dataString = dataset.data[index].toString();
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          var padding = 15;
          var position = element.tooltipPosition();
          ctx.fillText(dataset.title, position.x, position.y - (fontSize / 2) - padding);
        });
      }
    });
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="bubble-chart" width="800" height="800"></canvas>  
   </body>
</html>

Related Tutorials