如何为chart.js(chartjs.org)中的所有图表类型添加标签/图例?

Nal*_*lin 59 javascript chart.js

chart.js的文档提到了"图例模板",但没有提供此类图例的资源或示例.这些如何显示?

小智 58

您可以在图表选项中包含图例模板:

//legendTemplate takes a template as a string, you can populate the template with values from your dataset 
var options = {
  legendTemplate : '<ul>'
                  +'<% for (var i=0; i<datasets.length; i++) { %>'
                    +'<li>'
                    +'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
                    +'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
                  +'</li>'
                +'<% } %>'
              +'</ul>'
  }

  //don't forget to pass options in when creating new Chart
  var lineChart = new Chart(element).Line(data, options);

  //then you just need to generate the legend
  var legend = lineChart.generateLegend();

  //and append it to your page somewhere
  $('#chart').append(legend);
Run Code Online (Sandbox Code Playgroud)

你还需要添加一些基本的CSS以使它看起来不错.

  • 请注意,您需要将"lineColor"更改为您正在使用的任何内容; 例如,在折线图中,您应该使用pointColor.您可能还想在span中添加一些内容,例如if语句. (4认同)
  • 仅供参考,使用的模板引擎是John Resig的微模板 - http://ejohn.org/blog/javascript-micro-templating/(来自Chart.js代码注释) (3认同)

Zan*_*ken 44

  1. 图例是ChartJs库的默认选项的一部分.因此,您无需将其明确添加为选项.

  2. 该库生成HTML.只需将其添加到您的页面即可.例如,将其添加到给定DIV的innerHTML.(如果您正在编辑颜色,请编辑默认选项等)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
Run Code Online (Sandbox Code Playgroud)

  • 如何改变颜色? (12认同)

小智 13

奇怪的是,我没有在Chart.js文档中找到任何关于图例和标签的内容.好像你不能单独使用chart.js.

我使用了非常轻的https://github.com/bebraw/Chart.js.legend来生成传说.