chart.js的文档提到了“图例模板”,但没有提供此类图例的资源或示例。如何显示这些内容?
发布于 2014-08-15 22:43:35
您可以在图表选项中包括图例模板:
//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来让它看起来不错。
发布于 2014-03-11 03:56:13
奇怪的是,我在Chart.js文档中没有找到任何关于图例和标签的东西。似乎你不能单独使用chart.js来做这件事。
我使用了非常轻便的https://github.com/bebraw/Chart.js.legend来生成图例。
发布于 2016-04-06 10:27:31
对于折线图,我使用以下代码。
首先创建自定义样式
.boxx{
position: relative;
width: 20px;
height: 20px;
border-radius: 3px;
}
然后在您的行选项中添加以下内容
var lineOptions = {
legendTemplate : '<table>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
+'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
+'<% } %>'
+'</table>',
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();
别忘了添加
<div id="legendDiv"></div>
在你的html上,你想把你的图例放在哪里?就这样!
https://stackoverflow.com/questions/20397512
复制相似问题