首页 > 解决方案 > Angular JS 中的条形图使用 Chartjs

问题描述

我正在我的 AngularJS 应用程序中使用 Chartjs 制作条形图。我能够渲染图表,但是,我无法找到一种方法来显示每个条形图的值。我找到的解决方案是针对 Angular 应用程序而不是针对 AngularJs 应用程序的。

这是我的画布标签:

我的 JS 文件代码:

     $scope.labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July'];
    $scope.data = [[75, 63, 59, 79, 13, 91, 113]];
    $scope.ColorBar = ['#90EE90', '#FF6600'];
    $scope.DataSetOverride = [{ yAxisID: 'y-axis-1' }];
    $scope.options = {
        legend: { display: true },
        responsive: true, 
        scales: {
            yAxes: [
                {
                    id: 'y-axis-1',
                    type: 'linear',
                    display: true,
                    position: 'left'
                }]
             }
           }

标签: angularjschart.jsbar-chart

解决方案


如果您不想使用 datalabels 插件,您可以编写自己的基本版本作为内联插件,如下所示:

const customDatalabalesPlugin = {
  id: 'customDatalabels',
  afterDatasetsDraw: (chart, args, opts) => {
    const {
      ctx,
      _metasets
    } = chart;
    const lineHeight = ctx.measureText('M').width;
    const color = opts.color || 'black';

    for (let i = 0; i < chart.data.datasets.length; i++) {
      const meta = chart.getDatasetMeta(i)
      meta.data.forEach((el) => {
        //console.log(el)
        const dpVal = el._chart.data.datasets[el._datasetIndex].data[el._index];
        const text = dpVal.toString();
        const textWidth = ctx.measureText(text).width;

        ctx.fillStyle = color;
        ctx.fillText(text, (el._model.x - textWidth / 2), (el._model.y - lineHeight));
      });
    }
  }
}

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12.4, 19.234, 3.23213, 5.4, 2, 3],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      customDatalabels: {
        color: 'green', // Color each character individual collor
        // color: 'pink' // Color whole label this collor
      }
    }
  },
  plugins: [customDatalabalesPlugin]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

关于在插件中使用私有变量,可以节省地完成,因为chart.js 不会再发布版本2,因此它们不会再被更改。


推荐阅读