如何在 Chart.js 2.1.6 的图例中显示条形标签?

How to show bar labels in legend in Chart.js 2.1.6?(如何在 Chart.js 2.1.6 的图例中显示条形标签?)

本文介绍了如何在 Chart.js 2.1.6 的图例中显示条形标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Chart.js 创建图表,我想在图例中显示条形的标签,不是数据集的标题(只有一个),请参见下文以图片为例:

I'm creating charts using Chart.js and I want to show the labels for the bars in the legend, not the title of the dataset (there is only one), please see the below image as an example:

我目前的图例如下所示:

My current legend just looks like this:

我浏览了文档但无济于事,实际上我发现它们非常混乱.

I have looked through the docs but to no avail, I found them very confusing actually.

这是我当前的代码:

var chart_0 = new Chart($('#cp_chart_0'), {
      type: 'bar'
    , data: {
          labels: ['Blue','Green','Yellow','Red','Purple','Orange']
        , datasets: [{
              label: 'Dataset 1'
            , borderWidth: 0
            , backgroundColor: ['#2C79C5','#7FA830','#7B57C3','#ED4D40','#EC802F','#1DC6D3']
            , data: ['12','2','5','0','9','1']
        }]
      }
});

谢谢!

推荐答案

最简单的方法是为您的数据提供多个集合:

Easiest way is to provide your data with multiple sets :

  data: {
      labels: ['total votes']
    , datasets: [{
          label: 'Blue'
        , backgroundColor: ['#2C79C5']
        , data: ['12']
    },{
          label: 'Green'
        , backgroundColor: ['#7FA830']
        , data: ['2']
    },
    ...
    ]
  }

但是您可以使用 generateLabels 生成自定义标签 - http://www.chartjs.org/docs/#chart-configuration-legend-configuration

But you can generate a custom labels using generateLabels - http://www.chartjs.org/docs/#chart-configuration-legend-configuration

甚至可以自定义整个图例,包括格式,使用 legendCallback - http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration

Or even customise the whole legend, including formatting, with legendCallback - http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration

这篇关于如何在 Chart.js 2.1.6 的图例中显示条形标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 Chart.js 2.1.6 的图例中显示条形标签?

基础教程推荐