简体   繁体   中英

Display data label (legend) in line-chart using chartjs

I am using chartjs to display a line chart.

The problem is that I want to display labels or a legend for both data sets below the chart. It should display the color and a textual description of the data set.

 var ctx = document.getElementById("myChart").getContext("2d"); var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", 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: "My Second dataset", 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(ctx).Line(data); 
 <script src="http://www.chartjs.org/assets/Chart.js"></script> <canvas id="myChart" width="400" height="400"></canvas> 

How can I do this?

Use generateLegend to get the legend HTML and put in the HTML element of your choice.

document.getElementById("legend").innerHTML = myLineChart.generateLegend();

with HTML

<div id="legend"></div>

You'd also want to style it

#legend ul {
    list-style: none;
    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
    font-size: 12px;
}

#legend ul span {
    display: inline-block;
    height: 1em;
    width: 1em;
    margin-right: 0.5em;
}

Fiddle - http://jsfiddle.net/0hagvdas/


在此处输入图片说明

How to display data labels? I tried to use Index Labels. Check out: https://plnkr.co/edit/gdOEKze1QdzzinUwryCy?p=preview

var dataThird = {
label: "s3",
data: {
indexLabel: 'dataPoints',
indexLabelPlacement: 'outside',  
indexLabelOrientation: 'horizontal',
dataPoints: [45220, 49450, 79880, 21690, 15112, 22452, 34400, 34227]
},
lineTension: 0.3,
fill: false,
borderColor: '#89da59',
backgroundColor: 'transparent',
pointBorderColor: '#89da59',
pointBackgroundColor: '#89da59',
pointRadius: 5,
pointHoverRadius: 7,
pointHitRadius: 30,
pointBorderWidth: 2,
pointStyle: 'circle'};

check my example where i added options: { legend: { display: true, position:'bottom' }

for legend below chart here is hyper link [ https://jsfiddle.net/hiren65/xer2qvph/4/][1]

[1]: https://jsfiddle.net/hiren65/xer2qvph/4/ enter code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM