How to show data values on top of each bar in chart.js

134 Views

How to show data values on top of each bar in chart.js

Chart.js | show data values on top of each bar

This is an example of displaying data value on top of each bar of Chart.js in the web page.

Step 1: Create a basic html file called "chart.html" .

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Bar Chart</title>
  </head>
	<body>
		
	</body>
</html>

 

Step 2: Add a "Chart.min.js" CDN link inside the "head" tag.

 <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Bar chart with data value on the top of each bar</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
</head>

If you don't want to use CDN server then you can download "chart.js" JavaScript plugin from www.chartjs.org

 

Step 3: Now add a canvas element in the body element.

 <body>
    <div class="chart-container" style="position: relative; width:80vw">
        <canvas id="my_Chart"></canvas>
    </div>
</body>

Here div element is use to manage chart area like position, width etc.

 

Step 4: Now add some javascript to bind the canvas element to drow bar chart

 <body>
    <div class="chart-container" style="position: relative; width:80vw">
        <canvas id="my_Chart"></canvas>
    </div>

    <script>

        // data define for bar chart

        var myData = {
            labels: ["Javascript", "Java", "Python", "PHP", "C++", "TypeScript", "Linux Shell","C","Ruby on Rails"],
            datasets: [{
                label: "Hey, baby!",
                fill: false,
                backgroundColor: ['#ff0000', '#ff4000', '#ff8000', '#ffbf00', '#ffbf00', '#ffff00', '#bfff00', '#80ff00', '#40ff00', '#00ff00'],
                borderColor: 'black',
                data: [85, 60,70, 50, 18, 20, 45, 30, 20],
            }]
        };

        
        // Options define for display value on top of bars
			
        var myoption = {
            tooltips: {
                enabled: true
            },
            hover: {
                animationDuration: 1
            },
            animation: {
            duration: 1,
            onComplete: function () {
                var chartInstance = this.chart,
                    ctx = chartInstance.ctx;
                    ctx.textAlign = 'center';
                    ctx.fillStyle = "rgba(0, 0, 0, 1)";
                    ctx.textBaseline = 'bottom';

                    // Loop through each data in the datasets

                    this.data.datasets.forEach(function (dataset, i) {  
                        var meta = chartInstance.controller.getDatasetMeta(i);
                        meta.data.forEach(function (bar, index) {
                            var data = dataset.data[index];
                            ctx.fillText(data, bar._model.x, bar._model.y - 5);

                        });
                    });
                }
            }
        };

        
        // Code to draw Chart
        
        var ctx = document.getElementById('my_Chart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',        // Define chart type
            data: myData,    	// Chart data
            options: myoption 	// Chart Options [This is optional paramenter use to add some extra things in the chart].
        });
    </script>
</body>

 

The complete code is here. You can simply copy and paste the bellow code to draw a bar chart in your page with data values on top of each bar.

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Bar chart with data value on the top of each bar</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
  </head>
	<body>
		
        <div class="chart-container" style="position: relative; width:80vw">
            <canvas id="my_Chart"></canvas>
        </div>
		

		<script>

			// Data define for bar chart

			var myData = {
				labels: ["Javascript", "Java", "Python", "PHP", "C++", "TypeScript", "Linux Shell","C","Ruby on Rails"],
				datasets: [{
					label: "Hey, baby!",
					fill: false,
					backgroundColor: ['#ff0000', '#ff4000', '#ff8000', '#ffbf00', '#ffbf00', '#ffff00', '#bfff00', '#80ff00', '#40ff00', '#00ff00'],
					borderColor: 'black',
					data: [85, 60,70, 50, 18, 20, 45, 30, 20],
				}]
			};
			
			// Options to display value on top of bars
			
			var myoption = {
				tooltips: {
					enabled: true
				},
				hover: {
					animationDuration: 1
				},
				animation: {
				duration: 1,
				onComplete: function () {
					var chartInstance = this.chart,
						ctx = chartInstance.ctx;
						ctx.textAlign = 'center';
						ctx.fillStyle = "rgba(0, 0, 0, 1)";
						ctx.textBaseline = 'bottom';

						this.data.datasets.forEach(function (dataset, i) {
							var meta = chartInstance.controller.getDatasetMeta(i);
							meta.data.forEach(function (bar, index) {
								var data = dataset.data[index];
								ctx.fillText(data, bar._model.x, bar._model.y - 5);

							});
						});
					}
				}
			};

			
			//Code to drow Chart

			var ctx = document.getElementById('my_Chart').getContext('2d');
			var myChart = new Chart(ctx, {
				type: 'bar',    	// Define chart type
				data: myData,    	// Chart data
				options: myoption 	// Chart Options [This is optional paramenter use to add some extra things in the chart].
			});

		</script>
	</body>
</html>