如何为chart.js(chartjs.org)中的所有图表类型添加标签/图例? [英] How can labels/legends be added for all chart types in chart.js (chartjs.org)?

查看:167
本文介绍了如何为chart.js(chartjs.org)中的所有图表类型添加标签/图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The documentation for chart.js mentions "legend templates" but gives no resources or examples of such legends. How can these be displayed?

推荐答案

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

You can include a legend template in the chart options:

//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);

你还需要添加一些基本的css才能让它看起来不错。

You'll also need to add some basic css to get it looking ok.

这篇关于如何为chart.js(chartjs.org)中的所有图表类型添加标签/图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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