如何使用Chart.js在堆积条形图中显示内联值?

时间:2017-11-03 23:37:09

标签: javascript graph chart.js

我正在使用Chart.js库来显示堆叠条形图中的一些值,但我正在努力寻找如何显示条形图内部的值,即

enter image description here

现在,我有以下代码显示栏顶部的数字,但我想知道如何在栏内显示它们。



var numberWithCommas = function(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
    type: 'bar',
    data: {
        labels: dates,
        datasets: [
        {
            label: 'SoftEnterprises, Sales',
            data: dataPack1,
						backgroundColor: "rgba(55, 160, 225, 0.7)",
						hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
						hoverBorderWidth: 2,
						hoverBorderColor: 'lightgrey'
        },
        {
            label: 'SmartSystems, Sales',
            data: dataPack2,
						backgroundColor: "rgba(225, 58, 55, 0.7)",
						hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
						hoverBorderWidth: 2,
						hoverBorderColor: 'lightgrey'
        },
        ]
    },
    options: {
     		animation: {
        	duration: 10,
          onComplete: function(){
                var chartInstance = this.chart,
                ctx = chartInstance.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';
                ctx.fillStyle = '#000';
                                this.data.datasets.forEach(function(dataset, i) {
                var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
                if (!isHidden) { //if dataset is not hidden
                    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);
                });
               }
            });
          
          }
        },
        tooltips: {
					mode: 'label',
          callbacks: {
          label: function(tooltipItem, data) { 
          	return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
          }
          }
         },
        scales: {
          xAxes: [{ 
          	stacked: true, 
            gridLines: { display: false },
            }],
          yAxes: [{ 
          	stacked: true, 
            ticks: {
        			callback: function(value) { return numberWithCommas(value); 
              },
     				}, 
            }],
        }, // scales
        legend: {display: true}
    } // options
   },
   
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

<canvas id="bar-chart" width="600" height="350"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

这可以使用名为chartjs-plugin-datalabels的Chart.js插件轻松实现。

以下是此插件需要设置的最小选项,以显示堆叠条形图的(中间)内的值:

options: { //your chart options
   plugins: {
      datalabels: {
         display: true,
         align: 'center',
         anchor: 'center'
      }
   }
}

尽管如此,您可以使用大量其他选项来进一步自定义这些值/标签(内部栏),可以找到here

ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇᴀᴍᴘʟᴇ

var numberWithCommas = function(x) {
   return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

var dataPack1 = [50000, 22000, 26000, 35000, 55000, 55000, 56000, 59000, 60000, 61000, 60100, 62000];

var dataPack2 = [0, 6000, 13000, 14000, 50060, 20030, 20070, 35000, 41000, 4020, 40030, 70050];

var dates = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';

var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
   type: 'bar',
   data: {
      labels: dates,
      datasets: [{
         label: 'SoftEnterprises, Sales',
         data: dataPack1,
         backgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, {
         label: 'SmartSystems, Sales',
         data: dataPack2,
         backgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
         hoverBorderWidth: 2,
         hoverBorderColor: 'lightgrey'
      }, ]
   },
   options: {
      tooltips: {
         mode: 'label',
         callbacks: {
            label: function(tooltipItem, data) {
               return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
            }
         }
      },
      scales: {
         xAxes: [{
            stacked: true,
            gridLines: {
               display: false
            },
         }],
         yAxes: [{
            stacked: true,
            ticks: {
               callback: function(value) {
                  return numberWithCommas(value);
               },
            },
         }],
      }, // scales
      legend: {
         display: true
      },
      plugins: {
         datalabels: {
            display: true,
            align: 'center',
            anchor: 'center'
         }
      }
   } // options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>


<canvas id="bar-chart" width="600" height="350"></canvas>