score:63
After looking into the Chart.Bar.js file I've managed to find the solution. I've used this function to generate a random color:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
I've added it to the end of the file and i called this function right inside the "fillColor:" under
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
so now it looks like this:
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
fillColor : getRandomColor(),
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
and it works I get different color for each bar.
score:0
I have just got this issue recently, and here is my solution
var labels = ["001", "002", "003", "004", "005", "006", "007"];
var data = [20, 59, 80, 81, 56, 55, 40];
for (var i = 0, len = labels.length; i < len; i++) {
background_colors.push(getRandomColor());// I use @Benjamin method here
}
var barChartData = {
labels: labels,
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
backgroundColor: background_colors,
data: data
}]
};
score:0
Code based on the following pull request:
datapoint.color = 'hsl(' + (360 * index / data.length) + ', 100%, 50%)';
score:0
what I've done is create a random color generator as many here have suggested
function dynamicColors() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgba(" + r + "," + g + "," + b + ", 0.5)";
}
and then coded this
var chartContext = document.getElementById('line-chart');
let lineChart = new Chart(chartContext, {
type: 'bar',
data : {
labels: <?php echo json_encode($names); ?>,
datasets: [{
data : <?php echo json_encode($salaries); ?>,
borderWidth: 1,
backgroundColor: dynamicColors,
}]
}
,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
maintainAspectRatio: false,
}
});
Notice there is no parantheses at the function call This enables the code to call the function every time, instead of making an array This also prevents the code from using the same color for all the bars
score:0
Pass a color parameter in dataPoints like below for each bar:
{y: your value, label: your value, color: your color code}
score:0
function getRandomColor() {
const colors = [];
var obj = @json($year);
const length = Object.keys(obj).length;
for(let j=0; j<length; j++ )
{
const letters = '0123456789ABCDEF'.split('');
let color = '#';
for (let i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
colors.push(color);
}
return colors;
}
use this function for different colors
score:1
try this :
function getChartJs() {
**var dynamicColors = function () {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
}**
$.ajax({
type: "POST",
url: "ADMIN_DEFAULT.aspx/GetChartByJenisKerusakan",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var labels = r.d[0];
var series1 = r.d[1];
var data = {
labels: r.d[0],
datasets: [
{
label: "My First dataset",
data: series1,
strokeColor: "#77a8a8",
pointColor: "#eca1a6"
}
]
};
var ctx = $("#bar_chart").get(0).getContext('2d');
ctx.canvas.height = 300;
ctx.canvas.width = 500;
var lineChart = new Chart(ctx).Bar(data, {
bezierCurve: false,
title:
{
display: true,
text: "ProductWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
});
$.each(r.d, function (key, value) {
**lineChart.datasets[0].bars[key].fillColor = dynamicColors();
lineChart.datasets[0].bars[key].fillColor = dynamicColors();**
lineChart.update();
});
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
score:1
This works for me in the current version 2.7.1
:
function colorizePercentageChart(myObjBar) {
var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {
var color = "green";
if(parseFloat(bars[i]) < 95){
color = "yellow";
}
if(parseFloat(bars[i]) < 50){
color = "red";
}
console.log(color);
myObjBar.data.datasets[0].backgroundColor[i] = color;
}
myObjBar.update();
}
score:1
Taking the other answer, here is a quick fix if you want to get a list with random colors for each bar:
function getRandomColor(n) {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
var colors = [];
for(var j = 0; j < n; j++){
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
colors.push(color);
color = '#';
}
return colors;
}
Now you could use this function in the backgroundColor field in data:
data: {
labels: count[0],
datasets: [{
label: 'Registros en BDs',
data: count[1],
backgroundColor: getRandomColor(count[1].length)
}]
}
score:1
If you know which colors you want, you can specify color properties in an array, like so:
backgroundColor: [
'rgba(75, 192, 192, 1)',
...
],
borderColor: [
'rgba(75, 192, 192, 1)',
...
],
score:2
If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:
Replace this line:
fillColor : dataset.fillColor,
For this one:
fillColor : dataset.fillColor[index],
The resulting code:
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset,datasetIndex){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
bars : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
//Replace this -> fillColor : dataset.fillColor,
// Whith the following:
fillColor : dataset.fillColor[index],
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
},this);
And in your js:
datasets: [
{
label: "My First dataset",
fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [2000, 1500, 1750, 50]
}
]
score:3
here is how I dealed: I pushed an array "colors", with same number of entries than number of datas. For this I added a function "getRandomColor" at the end of the script. Hope it helps...
for (var i in arr) {
customers.push(arr[i].customer);
nb_cases.push(arr[i].nb_cases);
colors.push(getRandomColor());
}
window.onload = function() {
var config = {
type: 'pie',
data: {
labels: customers,
datasets: [{
label: "Nomber of cases by customers",
data: nb_cases,
fill: true,
backgroundColor: colors
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Cases by customers"
},
}
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
score:7
Here's a way to generate consistent random colors using color-hash
const colorHash = new ColorHash()
const datasets = [{
label: 'Balance',
data: _.values(balances),
backgroundColor: _.keys(balances).map(name => colorHash.hex(name))
}]
score:11
Generate random colors;
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
and call it for each record;
function getRandomColorEachEmployee(count) {
var data =[];
for (var i = 0; i < count; i++) {
data.push(getRandomColor());
}
return data;
}
finally set colors;
var data = {
labels: jsonData.employees, // your labels
datasets: [{
data: jsonData.approvedRatios, // your data
backgroundColor: getRandomColorEachEmployee(jsonData.employees.length)
}]
};
score:17
As of August 2019, Chart.js now has this functionality built in.
You simply need to provide an array to backgroundColor.
Example taken from https://www.chartjs.org/docs/latest/getting-started/
Before:
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
After:
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: ['rgb(255, 99, 132)','rgb(0, 255, 0)','rgb(255, 99, 132)','rgb(128, 255, 0)','rgb(0, 255, 255)','rgb(255, 255, 0)','rgb(255, 255, 128)'],
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
I just tested this method and it works. Each bar has a different color.
score:18
Here, I solved this issue by making two functions.
1. dynamicColors() to generate random color
function dynamicColors() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgba(" + r + "," + g + "," + b + ", 0.5)";
}
2. poolColors() to create array of colors
function poolColors(a) {
var pool = [];
for(i = 0; i < a; i++) {
pool.push(dynamicColors());
}
return pool;
}
Then, just pass it
datasets: [{
data: arrData,
backgroundColor: poolColors(arrData.length),
borderColor: poolColors(arrData.length),
borderWidth: 1
}]
score:22
You can call this function which generates random colors for each bars
var randomColorGenerator = function () {
return '#' + (Math.random().toString(16) + '0000000').slice(2, 8);
};
var barChartData = {
labels: ["001", "002", "003", "004", "005", "006", "007"],
datasets: [
{
label: "My First dataset",
fillColor: randomColorGenerator(),
strokeColor: randomColorGenerator(),
highlightFill: randomColorGenerator(),
highlightStroke: randomColorGenerator(),
data: [20, 59, 80, 81, 56, 55, 40]
}
]
};
score:26
If you take a look at the library "ChartNew" which builds upon Chart.js you can do this by passing the values in as an array like so:
var data = {
labels: ["Batman", "Iron Man", "Captain America", "Robin"],
datasets: [
{
label: "My First dataset",
fillColor: ["rgba(220,220,220,0.5)", "navy", "red", "orange"],
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [2000, 1500, 1750, 50]
}
]
};
score:68
Solution: call the update method to set new values :
var barChartData = {
labels: ["January", "February", "March"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [20, 59, 80]
}
]
};
window.onload = function(){
var ctx = document.getElementById("mycanvas").getContext("2d");
window.myObjBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
//nuevos colores
myObjBar.datasets[0].bars[0].fillColor = "green"; //bar 1
myObjBar.datasets[0].bars[1].fillColor = "orange"; //bar 2
myObjBar.datasets[0].bars[2].fillColor = "red"; //bar 3
myObjBar.update();
}
score:92
As of v2, you can simply specify an array of values to correspond to a color for each bar via the backgroundColor
property:
datasets: [{
label: "My First dataset",
data: [20, 59, 80, 81, 56, 55, 40],
backgroundColor: ["red", "blue", "green", "blue", "red", "blue"],
}],
This is also possible for the borderColor
, hoverBackgroundColor
, hoverBorderColor
.
From the documentation on the Bar Chart Dataset Properties:
Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on.
Source: stackoverflow.com
Related Query
- Different color for each bar in a bar chart; ChartJS
- Different color for each column in angular-chartjs bar chart
- Different color for each bar in a bar graph in ChartJS and VueJS
- Angular 4: Different color for bar in bar chart dynamically using ChartJS
- How to set a full length background color for each bar in chartjs bar
- Gradient color for each bar in a bar graph using ChartJS
- chart js - Apply different color for each x-axes label
- How to use set the color for each bar in a bar chart using chartjs?
- Issue with chartjs linear gradient for the mixed bar chart in ReactJS is not calculated for each individual Bars
- How do I get a different label for each bar in a bar chart in ChartJS?
- Set different color for each bars using ChartJS in Angular 4
- subcategories for each bar in multibar chart using chartjs
- how to create bar chart with group and sam color for each group using chart.js?
- Chartjs random colors for each part of pie chart with data dynamically from database
- chart.js Line chart with different background colors for each section
- ChartJS bar chart with legend which corresponds to each bar
- Border radius for the bar chart in ChartJS
- Can I specify a different font size for each row of text in Chart Title?
- Chartjs - data format for bar chart with multi-level x-axes
- Grouping the object by key for Chartjs bar chart
- Different color for line segments in ChartJS
- How to set single color on each bar in angular chart js
- ChartJS bar chart fixed width for dynamic data sets
- Vue ChartKick - different colours for bar chart
- chartjs custom y axis values, different text for each one
- how to set color for each item in tooltip with ChartJS
- Is there any way to use 2 different color for the same bar in a chart?
- How to show different product name for every bar in chart js
- Minimum value for x Axis doesn't work for horizontal bar chart | ChartJS
- ChartJS horizontal chart display legend on each bar
More Query from same tag
- How to draw one line with different colors in chartjs2?
- First point on scatter plot on JavaScript chart.js not showing
- Charts js and laravel: Render chart after passing in json data
- Using chartjs-plugin-annotation with ng2-charts
- How can i change a numpy.ndarray to point format with curly brackets - Python 3.7
- Chart disappears just after finishing animation
- ChartJS plot not showing as it should be when toggling a grouped legend element
- How can I display desired/particular chart in App.vue from Charts.vue which contains different charts in Vuejs
- donut chart tooltip under center text
- How to always show line chart tooltip in ionic-angular.?
- chart.js - problems with axes options - what am I doing wrong?
- ChartJS showing incorrect data on the X-Axes
- charts disappear if rendered in hidden divs
- Unable to draw method in Chart.js, v2 can't be found
- How to Draw a line on chart without a plot point using chart.js
- How can I show "No Data" message in Pie Chart when there is no data using VueJS?
- ChartJS in Datatable cell performance
- Chart.JS Multiline Chart with unknown numbers of Lines from JSON
- chart js same label, multi data
- ChartJS Line Graph - Multiple Lines, Show one Value on Tooltip
- Reducing Y-axis in chart.js
- How can I change the position of legends in chart.js?
- My chart.js canvas disappears after hide() function
- How to use GET method to choose the right table to show ChartJS graph?
- Want to multiple charts on same page with different data
- ChartJS Line chart causes browser crash
- Show chart.js animation only when user scroll on the specific DIV
- Having problems displaying multiple charts on a page
- Chart.JS - Wrong Y axis
- How can I show gridlines only of the even value ones withchartjs?