在chart.js中每列的条形图顶部显示值

8wtpewkr  于 5个月前  发布在  Chart.js
关注(0)|答案(1)|浏览(114)

我已经尝试了很多,以显示在字符顶部的值,但我不能这样做,请你能帮助我与此我也添加插件来显示数据。

<canvas id="myChart" width="200" height="100" aria-label="Hello ARIA World" role="img"></canvas>
<script>
  const ctx = document.getElementById('myChart');
  console.log({{sales_performance|safe}})
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      datasets: [{
        label: 'Sales',
        data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          display: false, // Hide the y-axis label
          beginAtZero: true
        }
      },
      plugins: {
        datalabels: {
          color: 'black', // Set the color of the data labels
          font: {
            weight: 'bold'
          },
          formatter: function(value, context) {
            return value; // Display the value on the bars
          }
        }
      }
    }
  });


</script>

字符串
我想在每个条形列的顶部显示值。

6fe3ivhb

6fe3ivhb1#

这是一个常见的错误,因为库没有注册,所以 chartjs-plugin-datalabels 无法工作。您必须按照文档中的说明注册库。
要将数据标签定位在条形图的顶部,您需要在dataLabels数组的每个对象中添加datalabels属性。您可以阅读定位配置。

datasets: [
  {
    ...
    datalabels: {
      align: 'top',
      anchor: 'end',
    },
  }
]

字符串
完整代码:

new Chart(ctx, {
    type: 'bar',
    data: {
      labels: [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'July',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec',
      ],
      datasets: [
        {
          label: 'Sales',
          data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
          borderWidth: 1,
          datalabels: {
            align: 'top',
            anchor: 'end',
          },
        },
      ],
    },
    options: {
      scales: {
        y: {
          display: false, // Hide the y-axis label
          beginAtZero: true,
        },
      },
      plugins: {
        datalabels: {
          color: 'black', // Set the color of the data labels
          font: {
            weight: 'bold',
          },
          formatter: function (value, context) {
            return value; // Display the value on the bars
          },
        },
      },
    },
    plugins: [ChartDataLabels],
  });


Demo @ StackBlitz

相关问题