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
- multiple charts js in page but with same tooltips (about last chart)
- JSON cyclic object value when posting data in ChartJS
- How can I append a calculated value to the end of a bar in Chart.JS?
- php to json to chart.js
- How to Update 2 dataset for 2 lines in a CharJS line graph?
- Different labels needed for second line graph, chart js
- Ionic: Doughnut Chart's legend occupies complete card in mobile, while on big screen chart and legend looks fine
- Show 'No data' in Pie when there is no data using VueJS and ChartJS?
- how do I change the textsize in of doughnut in react-chartjs-2?
- Chart.js v3 Fade Animation in delay
- How to add new Line but not in the first x axes
- Drawing line chart in chart.js placing dots only when value changes
- Remove zeroline in chartJS Horizontal Bar chart
- Charts.js - Colors for stacked bar on multi-series line/bar chart are not working
- Chart JS : Getting issue with draw bar chart
- Chart.js: How can I manually set Y-axis range?
- Chart JS not rendering on iOS devices
- Chart JS: is possible mix Scatter and bar chart in Chart JS?
- Failed to use Chart.js using Angular2
- How to fill my chart (chart.js) with my own data from API
- Vue pie chart show after a while (like show console with a warning)
- How can I display desired/particular chart in App.vue from Charts.vue which contains different charts in Vuejs
- Chart.js runs in JSFiddle but not local "Chart is not defined"
- Searchable label text Chartjs
- How do remove the bottom scale on a Chart.js bar chart
- ChartJS using AJAX call to retrieve data isn't rendering visualization
- populate chartjs ajax servlet
- Chart js - Polar Scatter Chart
- How to get the X position at a specified chart item index?
- Chart.js inside popup on leaflet?