score:1
You can use html to create your custom legend. Here is an example of how to creating a custom legend with custom title(and custom user interface).
function legendClickCallback(event) {
event = event || window.event;
var target = event.target || event.srcElement;
while (target.nodeName !== 'LI') {
target = target.parentElement;
}
var parent = target.parentElement;
var chartId = parseInt(parent.classList[0].split("-")[0], 10);
var chart = Chart.instances[chartId];
var index = Array.prototype.slice.call(parent.children).indexOf(target);
var meta = chart.getDatasetMeta(index);
if (meta.hidden === null) {
meta.hidden = !chart.data.datasets[index].hidden;
target.classList.add('hidden');
} else {
target.classList.remove('hidden');
meta.hidden = null;
}
chart.update();
}
var ctx = document.getElementById("myChart");
var myLegendContainer = document.getElementById("myChartLegend");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["values #1", "values #2"],
datasets: [
{
label: "One",
backgroundColor: "red",
data: [26,36]
},
{
label: "Two",
backgroundColor: "blue",
data: [34, 40]
}
]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
myLegendContainer.innerHTML = myChart.generateLegend();
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
legendItems[i].addEventListener("click", legendClickCallback, false);
}
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
[class="0-legend"] {
cursor: pointer;
list-style: none;
padding-left: 0;
}
[class="0-legend"] li {
display: inline-block;
padding: 0 5px;
}
[class="0-legend"] li.hidden {
text-decoration: line-through;
}
[class="0-legend"] li span {
border-radius: 5px;
display: inline-block;
height: 10px;
margin-right: 10px;
width: 10px;
}
.legend-box{
border-color: gray;
border-style: dashed;
margin-top: 25px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/Chart.bundle.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
<div class='legend-box'>
<span>Chart legend</span>
<div id="myChartLegend"></div>
</div>
</div>
</body>
</html>
I used the code of this example to create above example
score:1
You can override default legend option to generate your own legends. With this approach, however, you cannot style the label you are adding on top of the legends.
P.S: I'm using same example used by user pooyan.
var ctx = document.getElementById("myChart");
var myLegendContainer = document.getElementById("legends");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["values #1", "values #2"],
datasets: [
{
label: "One",
backgroundColor: "red",
data: [26,36]
},
{
label: "Two",
backgroundColor: "blue",
data: [34, 40]
}
]
},
options: {
legend: {
position: 'left',
labels : {
generateLabels: function(chart){
var data = chart.data;
var legends = Array.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
return {
text: dataset.label,
fillStyle: (!Array.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
hidden: !chart.isDatasetVisible(i),
lineCap: dataset.borderCapStyle,
lineDash: dataset.borderDash,
lineDashOffset: dataset.borderDashOffset,
lineJoin: dataset.borderJoinStyle,
lineWidth: dataset.borderWidth,
strokeStyle: dataset.borderColor,
pointStyle: dataset.pointStyle,
// Below is extra data used for toggling the datasets
datasetIndex: i
};
}, this) : [];
var title = {
text: 'My Cool Label',
strokeStyle: 'transparent',
fillStyle: 'transparent',
lineWidth: 0
};
legends.unshift(title);
return legends;
}
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
<script src="https://npmcdn.com/chart.js@2.7.2/dist/Chart.bundle.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
score:1
you can do that by using fillText() above the legend after having drawn the chart.
By example, use the plugin afterDatasetsDraw (or another) and draw the title up to the position of first element of the legend (use legendHitBoxes[0]).
In the plugin section :
return {afterDatasetsDraw: function(chartInstance, easing) {
//onProgress: function (animation) {
//var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = 'center';
// ctx.fillStyle = "rgba(255, 243, 243)";
ctx.textBaseline = 'middle';
// Ajout d'un titre de légende
var titreLegendeX = chartInstance.legend.legendHitBoxes[0].left + 50;
var titreLegendeY = chartInstance.legend.legendHitBoxes[0].top-20;
ctx.fillStyle = "#000000";
ctx.font = "bold 12px verdana, sans-serif";
ctx.fillText("Titre de légende", titreLegendeX, titreLegendeY);
Example here To adapt for donut chart
Source: stackoverflow.com
Related Query
- How to add label for ChartJs Legend
- How to add the value for each label to pie legend
- How to change the color of legend in chartjs and be able to add one more legend?
- How to get onClick Event for a Label in ChartJS and React?
- How to add ChartJS code in Html2Pdf to view image
- How to add label in chart.js for polar chart area
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- How to add left padding for my charts done in ChartJs and my Google Map so it is not glued to the limit of the page on the left
- How to add additional label in the middle of each bar using ChartJS
- ChartJS - How to add Text between Pie Chart and Legend
- how to add extra label at zero levels in x-axis in chartjs
- How to dynamically update Chartjs legend label colors?
- How can I add functionality to Chartjs Doughnut chart custom legend
- How to add dataset legend in chartjs tooltip
- How can I add vertical line and label for each point in Chart.js?
- How to disable a tooltip for a specific dataset in ChartJS
- How to modify chartjs tooltip so i can add customized strings in tooltips
- show label in tooltip but not in x axis for chartjs line chart
- How to add second Y-axis for Bar and Line chart in Chart.js?
- how to always show label in chartjs without mouseover?
- How to hide the y axis and x axis line and label in my bar chart for chart.js
- Add zoom event handler to charts for chartjs with chartjs-plugin-zoom
- How to set a full length background color for each bar in chartjs bar
- how to change Y axis value dynamically based on user input in Chartjs for Line chart?
- PrimeNg bar chart how to show a label for the y-axis
- How to create custom legend in ChartJS
- How can I force my ChartJS canvas legend to stay in a single column?
- How to add background color between two lines in yAxis Chartjs
- How to Change the Label Strike-Through with light gray on a ChartJS Doughnut?
- How to remove bars for those bars with zero value in Chartjs bar chart?
More Query from same tag
- Remove zero values from tooltip
- Chartjs stacked bar separate tooltip for all stacked
- The title of my ChartJs on the chart is undefined, but I can't change it because my labels use a function: Object.keys(groupMedia)
- Chartjs to show more set of data of click of a button
- Vertical stacked bar chart using SharePoint List
- Using sticky figures above bars in chart.js
- Dynamic Pie Chart With Json Data using chart.js
- Is there any way to use 2 different color for the same bar in a chart?
- Chart.js data goes backwards when retroactively pushing datapoint from HTTP request using Angular
- Date range picker and chart js
- chart.js not allowing y axis steps with logarithmic scale
- Complex Javascript variables containing the values of other assigned variables?
- I want to change color of individual bar of bar graph
- Avoiding Empty Curly Braces in MongoDB Aggregation
- How to bind data from Controler to chartjs line chart to create it as dynamic?
- Change List<Object> into List<List<int>> using LINQ
- ChartJS AJAX Javascript
- How to add tooltips to chart.js graph
- Is it possible to set the background color of a sector in a radar chart in Chart.js?
- Unable to ES6 import ChartJS plugin into Aurelia
- How to show bar labels in legend in Chart.js 2.1.6?
- Change Chartjs Legend Icon Style
- Updating chart.js with a dataset of different size not working
- Specifying the legendTemplate in Chart.js when using asp (classic)
- Specify varying thickness of each bar in Chart.js bar chart
- Chart.js scatter chart stops working after extending to multiple datasets
- How to change colour of specific xAxis label in charts js
- How to set lower and upper bound in react react-chartjs-2?
- How we can draw a circle in bar chart
- How to customize border style on Chart.js