图表栏顶部可以有数字值吗? [英] Can we have number value on the top of charts bars.?

查看:44
本文介绍了图表栏顶部可以有数字值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户需要直接知道该值,而不是将鼠标悬停在该值上.谢谢.

User needs to know the value directly instead of mouse hovering on it. Thanks.

推荐答案

您可以使用 chartjs-plugin-datalabels .标签的定位由内部的以下定义指定图表选项.

You can use chartjs-plugin-datalabels. The positioning of the labels is specified by the following definition inside the chart options.

plugins: {
  datalabels: {        
    anchor: 'end',
    align: 'end',
  }
}

请查看下面的可运行代码段.

Please have a look at the runnable code snippet below.

const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O'];
const data = labels.map(l => Math.floor(Math.random() * 1000) + 1);
const sortedData = data.slice().sort((a, b) => a - b);
const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O'],
    datasets: [{
      label: "My Dataset",
      data: data,
      backgroundColor: backgroundColors
    }]
  },
  options: {
    layout: {
      padding: {
        top: 25
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    plugins: {
      datalabels: {        
        anchor: 'end',
        align: 'end',
      }
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<canvas id="myChart" height="90"></canvas>

这篇关于图表栏顶部可以有数字值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆