Chart.js - Override inherited colors when coloring graphs - javascript

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.

Related

How can i implement chart.js destroy in my draw function

I have a doughnut Chart that I would like to update with a new dataset each time I select a different option in my dropdown menu but because my code is in a draw() function, the chart constantly tries to draw itself over and over again which is why I keep getting the error message: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'myChart' can be reused.
How would I be able to fix this? The variable named stats is wat I'm trying to update my chart's data with.
var config = {
type: 'doughnut',
data: {
labels: legend,
datasets: [{
backgroundColor: ['rgb(204,0,0)', 'rgb(241,194,50)', 'rgb(41,134,204)', 'rgb(106,168,79)', 'rgb(255,62,153)'],
data: stats,
}]
},
plugins: [hoverLabel],
options: {
radius: this.radius,
hoverOffset: 30,
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: "Top 5 causes of death in " + country,
color: 'rgb(0,0,0)',
align: 'center',
padding: 15,
font: {
size: 25
}
},
legend: {
position: 'right',
title: {
display: true,
color: 'rgb(0,0,0)',
text: 'Legend',
font: {
weight: 'bold',
size: 20
},
},
labels: {
color: 'rgb(0,0,0)',
usePointStyle: true,
padding: 15,
font: {
size: 15,
weight: 'bold'
}
}
}
}
}
};
let mychart = new Chart('myChart', config);
Doughnut Chart
You have 2 options, either fully recreate the chart by destroying it first:
const config = {}; // Fill with your config opbject
let chart = Chart.getChart('myChart'); // Pass the canvas ID
if (chart) {
chart.destroy();
}
chart = new Chart('myChart', config);
or by updatingt the current chart instance:
const config = {}; // Fill with your config opbject
let chart = Chart.getChart('myChart'); // Pass the canvas ID
if (chart) {
chart.data.labels = legend;
chart.data.datasets[0].data = stats;
chart.update();
} else {
new Chart('myChart', config)
}

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

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'
}
}
}

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.

Multiline Legend Label with Pie Chartjs

I'm trying to have multiline labels with a pie chart on ChartJS. I've read on multiple questions that using an array of strings should get the job done, yet I'm not seeing it. My code is as follows:
var ctx = document.getElementById("pie-inversiones");
window.myBar = new Chart(ctx, {
type: 'pie',
data: pieInversiones,
options: {
legend: {
position: 'left',
onClick: function (e) {
e.stopPropagation();
},
labels: {
fontColor: "#15467D",
fontFamily: "Neo Sans Std",
fontSize: 10
}
},
animation: {
animateRotate: getParameterByName("action") == "print" ? false : true
},
plugins: {
datalabels: {
color: '#15467D',
anchor: "end",
align: "end",
formatter: (value, ctx) => {
return value + "%";
}
}
}
},
});
With the data object having two properties, dataset (data with the background color) and labels, which is just an array of arrays, each having 1+ strings in it.
Most questions I see ask about bar charts, how would I go about achieving this on a pie one?
Here's an example of the code I'm using https://jsfiddle.net/04zcy2hu/

Categories