score:-5
please check this documentation .
legend configuration
the chart legend displays data about the datasets that area appearing on the chart.
configuration options position of the legend. options are:
'top' 'left' 'bottom' 'right'
legend item interface
items passed to the legend onclick function are the ones returned from labels.generatelabels. these items must implement the following interface.
{
// label that will be displayed
text: string,
// fill style of the legend box
fillstyle: color,
// if true, this item represents a hidden dataset. label will be rendered with a strike-through effect
hidden: boolean,
// for box border. see https://developer.mozilla.org/en/docs/web/api/canvasrenderingcontext2d/linecap
linecap: string,
// for box border. see https://developer.mozilla.org/en-us/docs/web/api/canvasrenderingcontext2d/setlinedash
linedash: array[number],
// for box border. see https://developer.mozilla.org/en-us/docs/web/api/canvasrenderingcontext2d/linedashoffset
linedashoffset: number,
// for box border. see https://developer.mozilla.org/en-us/docs/web/api/canvasrenderingcontext2d/linejoin
linejoin: string,
// width of box border
linewidth: number,
// stroke style of the legend box
strokestyle: color
// point style of the legend box (only used if usepointstyle is true)
pointstyle: string
}
example
the following example will create a chart with the legend enabled and turn all of the text red in color.
var chart = new chart(ctx, { type: 'bar', data: data, options: { legend: { display: true, labels: { fontcolor: 'rgb(255, 99, 132)' } } } }); custom on click actions
it can be common to want to trigger different behaviour when clicking an item in the legend. this can be easily achieved using a callback in the config object.
the default legend click handler is:
function(e, legenditem) {
var index = legenditem.datasetindex;
var ci = this.chart;
var meta = ci.getdatasetmeta(index);
// see controller.isdatasetvisible comment
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
// we hid a dataset ... rerender the chart
ci.update();
}
lets say we wanted instead to link the display of the first two datasets. we could change the click handler accordingly.
var defaultlegendclickhandler = chart.defaults.global.legend.onclick;
var newlegendclickhandler = function (e, legenditem) {
var index = legenditem.datasetindex;
if (index > 1) {
// do the original logic
defaultlegendclickhandler(e, legenditem);
} else {
let ci = this.chart;
[ci.getdatasetmeta(0),
ci.getdatasetmeta(1)].foreach(function(meta) {
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
});
ci.update();
}
};
var chart = new chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
}
}
});
now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
html legends
sometimes you need a very complex legend. in these cases, it makes sense to generate an html legend. charts provide a generatelegend() method on their prototype that returns an html string for the legend.
to configure how this legend is generated, you can change the legendcallback config property.
var chart = new chart(ctx, {
type: 'line',
data: data,
options: {
legendcallback: function(chart) {
// return the html string here.
}
}
});
score:0
you can extract the legend markup.
data () {
return {
legendmarkup: ''
}
},
ready () {
this.legendmarkup = this._chart.generatelegend()
}
and in your template you can output it.
<div class="legend" ref="legend" v-html="legendmarkup"></div>
this._chart is the internal chartjs instance in vue-chartjs. so you can call all chartjs methods which are not exposed by vue-chartjs api over it.
however you can also use the legend generator. the usage is the same in vue. you can pass in the options, use callbacks etc.
score:9
i'm having the same problem trying to understand the documentation and this link might clarify the process of customize the legends:
https://codepen.io/michiel-nuovo/pen/rrarrv
the trick is to track a callback to build your own html structure and return this new structure to chartjs.
inside the options object:
legendcallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
text.push('<li><span style="background-color:' +
chart.data.datasets[0].backgroundcolor[i] + '">');
if (chart.data.labels[i]) {
text.push(chart.data.labels[i]);
}
text.push('</span></li>');
}
text.push('</ul>');
return text.join("");
}
second, you need a container to insert the new html and using the method mychart.generatelegend() to get the customized html:
$("#your-legend-container").html(mychart.generatelegend());
after that, if you need, track down the events:
$("#your-legend-container").on('click', "li", function() {
mychart.data.datasets[0].data[$(this).index()] += 50;
mychart.update();
console.log('legend: ' + data.datasets[0].data[$(this).index()]);
});
$('#mychart').on('click', function(evt) {
var activepoints = mychart.getelementsatevent(evt);
var firstpoint = activepoints[0];
if (firstpoint !== undefined) {
console.log('canvas: ' +
data.datasets[firstpoint._datasetindex].data[firstpoint._index]);
}
else {
mychart.data.labels.push("new");
mychart.data.datasets[0].data.push(100);
mychart.data.datasets[0].backgroundcolor.push("red");
mychart.options.animation.animaterotate = false;
mychart.options.animation.animatescale = false;
mychart.update();
$("#your-legend-container").html(mychart.generatelegend());
}
}
another solution that i found, if you don't need to change the html structure inside the legend, you can just insert the same html in your legend container and customize it by css, check this another link:
hope it works for you.
Source: stackoverflow.com
Related Query
- How to create custom legend in ChartJS
- How to create a custom tooltip for chartJS graph with data in JSON array in JavaScript?
- How can I add functionality to Chartjs Doughnut chart custom legend
- Custom Legend with ChartJS v2.0
- chartjs : how to set custom scale in bar chart
- How to add label for ChartJs Legend
- How to change the color of legend in chartjs and be able to add one more legend?
- How can I force my ChartJS canvas legend to stay in a single column?
- How to Create a Custom Logarithmic Axis in Chart.js
- How to add ChartJS code in Html2Pdf to view image
- How can I create custom tooltips for each data point in a graph?
- How to use custom rendering methods of chartJs through ng2-charts angular?
- Create an interactive custom tooltip for chartjs
- How to create a simple Gauge with ChartJS v3?
- How to create chartjs chart with data from database C#
- How to create a stacked graph using ChartJS
- How to create a rounded rectangle using ChartJS
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- How do I change axis, title, legend formatting on chartjs template
- How do I create a legend for a bar chart?
- Chartjs Custom Legend with Time on Y-axis
- how to increase space between legend and chart in chartjs (ng2charts ) using angular
- How do I create a chartjs bar chart?
- How to custom legend with react-chartjs-2
- How to toggle between Custom tooltip and normal tooltip in chartjs and angular
- How to format the left legend on chartjs
- ChartJS Pie Chart How default just show 2 legend datas
- Updating Chartjs to 2.5 with custom code
- ChartJs - stacked bar chart with groups - how to create second x-axis with stack id
- How to set Custom tooltip event with Chartjs version 2.X
More Query from same tag
- Chart.js legend position error
- chartjs Asp.net MVC Remote Data
- chart js draw line chart by points instead of by lines
- How do I implement the 'autoskip' feature in chartjs?
- Can we have both ajax and jquery scripts in one function?
- generate basic pie chart using chartjs
- How to put back the data with a switch?
- chart.js - problems with axes options - what am I doing wrong?
- Chartjs 2.0 alpha, how to have a static scale for y-axis
- setting chartjs global configuration using chartkick
- How to add an empty data point to a linechart on Chart.js?
- Second tab doesn't show the chart . Can anybody see why?
- JavaScript Error - Uncaught SyntaxError: Unexpected token {
- is there anything wrong with this If Condition in Javascript code?
- How can I add background color of length bars in chart (chartJS)?
- How can I place single data on the center in Chart.js?
- how to reset the graph/chart after zoomin, pan using chartjs
- Setting min and max values chart.js
- Line chart is showing under bar in combochart in chartjs
- How to make ng2-Chart Scrollable for large amount of data sets?
- ChartJS sees date in string as numbers
- Charts.js in Django: Charts cannot appear
- undefined labels piechart - chartjs
- react-chartjs-2 line chart with time on X-axes with multiple data sets plotted wrong
- Ng2-charts crosshair plugin not working in Angular
- Show values in Chart.js Pie chart parts
- No rendered annotation line on Line Chart
- Create a rounded bar graph with Angular and chartJS
- Rails chart.js data coffee script
- How to hide the tick marks of the axis in react-chartjs-2