The documentation for chart.js mentions "legend templates" but gives no resources or examples of such legends. How can these be displayed?
js (3.6. 0), you can control the Legend display with the following code: const options = { plugins: { ... legend: { position: "right", // by default it's top }, ... }, };
In the Chart editor, under the 'Setup' tab, click the 'Add Label' box, under the 'Label' section. Select the cell range that includes your chart data. You should see your selected data displayed as labels in your chart.
The chart legend displays data about the datasets that are appearing on the chart.
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);
You'll also need to add some basic css to get it looking ok.
The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With