Legend isnt moving to the right on my doughnut chart created with chart.js - javascript

For some reason, the legend on this doughnut chart created with chart.js is not moving to the right. Even tried adding the rule to chart creation itself instead of putting it in the variable
EDIT
With further inspection, it appears any options that are set to the legend do not appear to be working.
const mobileData = {
labels: ["Desktop", "Tablet", "Phons"],
datasets: [{
label: '# of Users',
data: [2000, 550, 500],
borderWidth: 0,
backgroundColor: [
'#7477BF',
'#78CF82',
'#51B6C8'
]
}]
};
const mobileOptions = {
legend: {
position: 'right',
labels: {
boxwidth: 20,
fontStyle: 'bold'
}
}
}
let mobileChart = new Chart(mobileCanvas, {
type: 'doughnut',
data: mobileData,
options: mobileOptions
});
Here's a fiddle to the project minus images.
https://jsfiddle.net/5j2ucpv6/3/

You are using the new V3 version of the lib instead of V2
So please read the migration guide from chart.js (https://www.chartjs.org/docs/latest/getting-started/v3-migration.html)
The legend options have been moved to the plugin section like this
options: {
plugins: {
legend: {
position: 'right'
}
}
}

Related

Chart.js - Override inherited colors when coloring graphs

I'm creating graphs with ChartJS, but they seem to inherit the default colors of some parent element. The graphs look like this:
I am dynamically creating the charts, depending on selections from the user. The ChartJS chart takes in an array of either primitives, or objects to use as the chart data. I'm using the following function to create the chart objects, and then using an array of these objects as the parameter for ChartJS:
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
color: color,
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
Then I create the master chart with this function:
function createIntervalChart(intervalDataObjects, datetimeInterval) {
const cnvs = document.createElement('canvas');
const ctx = $(cnvs);
var data = {
labels: datetimeInterval,
datasets: intervalDataObjects,
}
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Projected Load Profiles",
fontSize: 18,
fontColor: "#111",
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
elements: {
point: {
radius: 0
}
},
plugins: {
zoom: {
zoom: {
wheel: {
enabled: true
},
pinch: {
enabled: true
},
mode: 'xy',
}
},
title: {
text: "Estimated Load Profiles"
}
}
};
var chart = new Chart(ctx, {
type: "line",
data: data,
options: options
});
return cnvs;
}
When I check the console, I see distinct colors created by the random_rgb() function, but they all turn out grey.
Color: rgba(215,231,183,0.6)
Color: rgba(253,61,199,0.1)
Color: rgba(27,15,88,0.1)
Does anyone know how to create a ChartJS chart with custom colors? Or how to override inherited styling for these charts? Thank you
color is not a valid dataset property for a line chart. Use borderColor and optionally also backgroundColor (will be used for drawing the legend label box).
function getChartDataObject(data){
var title = data['metadata']['title'];
var color = random_rgba();
console.log(`Color: ${color}`);
var dataObject = {
label: title,
data: data['scaled_interval'],
borderColor: color, // <- to be changed
fill: false,
lineTension: 0,
radius: 1,
}
return dataObject;
}
For further information, please consult Dataset Properties from the Chart.js documentation.

Show data values in Chart.js bars (version 3)

There is a thread with many answers on this topic (Show values on top of bars in chart.js), but it's all about version 2.x
getDatasetMeta() has been deprecated:
https://www.chartjs.org/docs/3.0.2/getting-started/v3-migration.html
The "datalabels" plugin has not been ported to 3.x:
https://github.com/chartjs/chartjs-plugin-datalabels
Have you found any working solutions? How can data values be displayed on top of vertical barcharts (or next to horizontal barcharts)?
You can use the beta of the datalabels plugin.
Documentation: https://v2_0_0-rc_1--chartjs-plugin-datalabels.netlify.app/
Script tag: <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc/dist/chartjs-plugin-datalabels.min.js"></script>
Install command: npm i chartjs-plugin-datalabels#next
Live example:
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.3.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0-rc"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels); // first way of registering the plugin, registers them for all your charts
var myChart = new Chart(ctx, {
type: 'bar',
plugins: [ChartDataLabels], // second way of registering plugin, register plugin for only this chart
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
data: [12, 19, 3, 5, 2, 3],
label: 'Advisor Closed MTD',
backgroundColor: 'rgb(192,111,94)',
barThickness: 25,
datalabels: {
color: '#FFCE56'
}
}],
},
options: {
responsive: false,
plugins: {
datalabels: {
anchor: 'end', // remove this line to get label in middle of the bar
align: 'end',
formatter: (val) => (`${val}%`),
labels: {
value: {
color: 'blue'
}
}
}
}
}
});
</script>

several graph has the same legend in flot

I am using JQuery Flot graph plugin to plot some bar charts in a page. when I plot a graph by datas and option below:
var chartData = [{
label: 'success',
data: [[0,1],[1,1]],
bars: {
order: 0,
fillColor: '#fff'
},
color: '#fff'
}, {
label: 'fail',
data: [[0,3],[2,1]],
bars: {
order: 1,
fillColor: 'rgba(255,255,255,0.5)'
},
color: 'rgba(255,255,255,0.5)'
}];
var barChartOptions = {
...
legend:{
container: '.flot-chart-legends--bar',
backgroundOpacity: 0.5,
noColumns: 0,
lineWidth: 0,
labelBoxBorderColor: 'rgba(255,255,255,0)'
}
};
$.plot($('.flot-bar'), chartData, barChartOptions);
It works for my bar chart, however, the other charts which hasn't label attached the same label. How can I do for it? Please help!
I sovled it! Check the source code in flot.js and found the incorrect code as follow:
$(options.legend.container).html(table);
which makes all the selectors of container contained the same html. I corrected it like this:
placeholder.parent().find(options.legend.container).html(table);
and the html is only attahced to the right chart I want.

Any suggestion on how to override Chart JS Donut library

I have added a donut chart as shown below without the numbers.
I wanted to make the outer-border fixed like the first picture shown below and hide the inner border and I have used Chart JS.
Any way I can do that as the chart JS default there is only border-color?
var ctx = document.getElementById('freeChart');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: [30,70],
backgroundColor: ['#9f9fa6'],
borderColor: ['#9f9fa6','#9f9fa6'],
}],
},
options:{
cutoutPercentage: 80,
elements: {
arc: {
borderWidth: 1
}
}
}
});

Legend option destroys pie chart in Chart.js

My Chart.js pie is working fine, but when I add the legend option, it disappears, much to my dismay. Other options like title and animation work pretty well, only the legend options ruins the pie. I have looked at the code thoroughly, but can't figure out what I'm not doing right. Below is my code:
if ( $('#broadsheet_piechart_sample').length ) {
var ctx = document.getElementById("broadsheet_piechart_sample");
var data = {
datasets: [{
data: [10, 20, 30, 40, 50],
backgroundColor: ['#455C73', '#9B59B6', '#BDC3C7', '#26B99A', '#3498DB'],
}],
labels: ['Dark Gray', 'Purple', 'Gray', 'Green', 'Blue']
};
//options
var options = {
title: {
display: true,
position: "top",
text: "Test Pie Chart",
fontSize: 18,
fontColor: "#111"
},
animation: {
duration: 0
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
var broadsheet_piechart_sample = new Chart(ctx, {
data: data,
type: 'pie',
options: options
});
}
You are may using an old version which can cause this issue.
Please upgrade to the latest CharJs version (2.7.3).
Here is what I did for example : example Just exactly what you did.

Categories