Có hai giải pháp cho vấn đề của bạn:
1: Đây là một biểu đồ đường thẳng, nhưng có thể dễ dàng phù hợp với một biểu đồ thanh.
Chú giải là một phần của các tùy chọn mặc định của thư viện ChartJs. Vì vậy, bạn không cần thêm rõ ràng tùy chọn này.
Thư viện tạo ra HTML. Nó chỉ là vấn đề thêm rằng vào trang của bạn. Ví dụ, thêm nó vào innerHTML của một DIV đã cho. (Chỉnh sửa các tùy chọn mặc định nếu bạn đang chỉnh sửa màu sắc, vv)
<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>
2: Thêm một mẫu huyền thoại trong tùy chọn biểu đồ
Bạn sẽ cũng cần phải thêm một số css cơ bản để làm cho nó trông ok.
//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);
Một trong hai tùy chọn này sẽ hoạt động.
Trong trường hợp của bạn mã huyền thoại sẽ giống như thế này
(Giả sử bạn đã có một BarChart tạo)
<div id="legendDiv"></div>
document.getElementById("legendDiv").innerHTML = BarChart.generateLegend();
Sau đó sử dụng css để định dạng truyền thuyết tuy nhiên bạn muốn (bao gồm thêm khoảng cách giữa các huyền thoại trong biểu đồ)
Thêm một huyền thoại-div dưới bảng xếp hạng là một cách giải quyết hợp lý. – markE
Câu hỏi đặt ra là về labelString: "ProductName (ProductName)" không phải là về các truyền thuyết, huyền thoại là tất cả về trục y, đây là câu hỏi về trục x. – Thunder