Javascript Chartjs 条形图图例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27045840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:39:17  来源:igfitidea点击:

Chartjs Bar Chart Legend

javascriptchart.js

提问by r.oliver

I am having problems getting a legend to show up on the bar graph that I have created using chartjs. The documentation talks about a legend template, but I can't seem to find a good example of how to implement this into the graph. Below is the code I am using to generate the graph.

我在使用 chartjs 创建的条形图上显示图例时遇到问题。该文档讨论了图例模板,但我似乎无法找到一个很好的示例来说明如何将其实现到图表中。下面是我用来生成图表的代码。

<div style="width: 100%;">
  <canvas id="canvas" height="450" width="600"></canvas>
<div id="legendDiv">&nbsp;</div>
</div>
<script>
    var randomScalingFactor = function(){ return Math.round(Math.random()*100)};

    var barChartData = {
        labels : ["Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 7","Item 8","Item 9","Item 10","Item 11","Item 12","Item 13","Item 14","Item 15","Item 16","Item 17"]
        datasets : [
            {
                fillColor : "rgba(166,166,166,0.5)",
                strokeColor : "rgba(166,166,166,0.8)",
                highlightFill: "rgba(166,166,166,0.75)",
                highlightStroke: "rgba(166,166,166,1)",
                data : [10,4,3,4,3,6,4,1,10,3,3,10,2,4,10,3,4]

             },
            {
                fillColor : "rgba(196,64,54,0.5)",
                strokeColor : "rgba(196,64,54,0.8)",
                highlightFill : "rgba(196,64,54,0.75)",
                highlightStroke : "rgba(196,64,54,1)",
                data : [6,3,2,3,2,3,4,1,8,3,3,6,1,3,8,3,4]
            }
        ]

    }
    window.onload = function(){
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
        responsive : true
         });
     }

     </script>
 <div>

回答by Quince

THE BELOW ANSWER IS FOR CHARTJS 1.X

以下答案适用于 ChartJS 1.X

So below is an example of how you can set up a legend using the labels that need to be given which each dataset, using the default legend template all you have to do is call generateLegend()on the chart and then place this on the page

因此,下面是一个示例,说明如何使用需要为每个数据集指定的标签设置图例,使用默认图例模板,您只需generateLegend()在图表上调用,然后将其放在页面上

var helpers = Chart.helpers;
var canvas = document.getElementById('bar');
var randomScalingFactor = function() {
  return Math.round(Math.random() * 100)
};
var barChartData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
      label: "My First dataset",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",
      highlightFill: "rgba(220,220,220,0.75)",
      highlightStroke: "rgba(220,220,220,1)",
      data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
    }, {
      label: "My Second dataset",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",
      highlightFill: "rgba(151,187,205,0.75)",
      highlightStroke: "rgba(151,187,205,1)",
      data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
    }]

  }
  // 
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
  tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
  animation: false,
});
// 
var legendHolder = document.createElement('div');
legendHolder.innerHTML = bar.generateLegend();

document.getElementById('legend').appendChild(legendHolder.firstChild);
ul {
  list-style: none;
}
ul li {
  display: block;
  padding-left: 30px;
  position: relative;
  margin-bottom: 4px;
  border-radius: 5px;
  padding: 2px 8px 2px 28px;
  font-size: 14px;
  cursor: default;
  height:20px;
  width: 140px;
  -webkit-transition: background-color 200ms ease-in-out;
  -moz-transition: background-color 200ms ease-in-out;
  -o-transition: background-color 200ms ease-in-out;
  transition: background-color 200ms ease-in-out;
}
li span {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 20px;
  border-radius: 5px;
  height:20px
}

li span.bar-legend-text {
  left:25px;
  width:120px;
}
#chart-area > *{
  float:left
    }
<script src="https://raw.githack.com/chartjs/Chart.js/v1.1.1/Chart.min.js"></script>
<div id="chart-area">
  <canvas id="bar" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
  <div id="legend"></div>
</div>

http://jsfiddle.net/masiht/r5g6a3cd/

http://jsfiddle.net/masiht/r5g6a3cd/

回答by SaJ

I have an answer and it is working fine...

我有一个答案,它工作正常......

var ctx = document.getElementById("canvas").getContext("2d");
                        new Chart(ctx).HorizontalBar(barChartLocData, {
                            responsive: true,
                            scaleFontColor: "#000",
                            showTooltips: false,
                            onAnimationComplete: function() {
                                var ctx = this.chart.ctx;
                                ctx.font = this.scale.font;
                                ctx.fillStyle = this.scale.textColor
                                ctx.textAlign = "right";
                                ctx.textBaseline = "right";
                                this.datasets.forEach(function(dataset) {
                                    dataset.bars.forEach(function(bar) {
                                        ctx.fillText(bar.value, bar.x, bar.y - 5);
                                    });
                                });
                            }
                        });

回答by Sanyami Vaidya

Try this

尝试这个

    var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "My First dataset",
                fillColor: "rgba(151,187,205,0.5)",
                strokeColor: "rgba(151,187,205,0.8)",
                highlightFill: "rgba(151,187,205,0.75)",
                highlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };
    var context = document.getElementById('clients').getContext('2d');
    var clientsChart = new Chart(context).Bar(data);

HTML:

HTML:

 <canvas id="clients" width="450" height="350"></canvas>

http://jsfiddle.net/TZq6q/299/

http://jsfiddle.net/TZq6q/299/

回答by Robin Carlo Catacutan

For the latest Version 2.6.0, it can be done using legendCallback

对于最新的 2.6.0 版本,可以使用legendCallback来完成

Set the template for the legends:

设置图例的模板:

  legendCallback: function(chart) {
    var text = [];
    text.push('<ul>');
    for (var i=0; i<chart.data.datasets.length; i++) {
      console.log(chart.data.datasets[i]); // see what's inside the obj.
      text.push('<li>');
      text.push('<span style="background-color:' + chart.data.datasets[i].borderColor + '">' + chart.data.datasets[i].label + '</span>');
      text.push('</li>');
    }
    text.push('</ul>');
    return text.join("");
  },

Add html element to target for the location of the legends.

添加 html 元素以定位图例的位置。

<div id="chart-legends"></div>

Then generate the legends:

然后生成图例:

document.getElementById('chart-legends').innerHTML = myChart.generateLegend();