In this article, we’re going to focus on how we can give our background color a different way of coloring. Normally, you would be able to put in just an array with all these hardcoded values.
So first of all, this question came from one of my other posts about How to Create a Stacked Bar Chart Using Chart Js Example? which is an absolutely interesting topic. So a special thank you to our reader for asking the question.
So first of all, what we need to do is we need to create an HTML page and then add Chartjs CDN reference for getting started.
How to use set the color for each bar in a bar chart using chartjs?
In the Below example, we want the bars in this graph to have different colors that I choose myself i.e hard code fixed color. Because we don’t want to use random colors for each of the bars.
So now we have a bar chart. And basically quite simple, the easiest way to do coloring on the bar chart is basically with backgroundColor option.
backgroundColor: ["#ffb3b3", "#800000", "#b3ffec", "#009973", "#d5ff80", "#558000", "#ffdf80", "#997300", "#adadeb", "#24248f", "#6666ff","#000066"]
Real Time Example
<!DOCTYPE html>
<html>
<head>
<title>Set Different Color For Each Bar in a Bar Chart Using chart.js</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
</head>
<body>
<div style="margin-left:5%;margin-right:5%">
<canvas id="BarchatCanvas" style="width:80%"></canvas>
</div>
<script>
var BarchartData = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
datasets: [
{
label: "Projected sales",
backgroundColor: ["#ffb3b3", "#800000", "#b3ffec", "#009973", "#d5ff80", "#558000", "#ffdf80", "#997300", "#adadeb", "#24248f", "#6666ff","#000066"],
borderWidth: 1,
data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
}
]
};
const config = {
type: 'bar',
data: BarchartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
title: {
display: true,
text: "Bar Chart with Diffrent Color"
}
};
window.onload = function () {
new Chart("BarchatCanvas", config);
};
</script>
</body>
</html>
Different color for each bar in a bar chart with Random Color
if you need a different color for each bar in a Bar Chart then you can use the below example. Here we have created a callback function for backgroundColor that returns the random color for each bar in the bar chart.
backgroundColor: color => {
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)";
}
<!DOCTYPE html>
<html>
<head>
<title>Set Different Color For Each Bar based on value Using chart.js</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
</head>
<body>
<div style="margin-left:5%;margin-right:5%">
<canvas id="BarchatCanvas" style="width:80%"></canvas>
</div>
<script>
var BarchartData = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
datasets: [
{
label: "Projected sales",
backgroundColor: color => {
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)";
},
borderWidth: 1,
data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
}
]
};
const config = {
type: 'bar',
data: BarchartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
title: {
display: true,
text: "Bar Chart with Diffrent Color"
}
};
window.onload = function () {
new Chart("BarchatCanvas", config);
};
</script>
</body>
</html>
Code explanation
So what I’m going to do is a very simple trick, but it will only work for everything except for the line chart. So what I’m going to do here, I’m going to just delete the hardcoded backgroundColor array and here in the backgroundColor I’m going to create a callback function because remember in chart js you’re allowed to put in functions if they are indicated as scriptable. So border color and background color are scriptable items.
so what we’re going to do here is it’s going to put in a script, We’re going to make it a function because basically a callback function which will be based on the conditions and this will be set color.
What I want maybe first is to make sure you see this here. So let’s do a console walk for that. So you can see what we are able to see here. Save that refresh, open the developer tab and let’s see what’s going on.
You can see here the data index and value that’s based on what you want to know or the index number. So if you want to highlight only the last three values or the first three values, you could do it based on condition.
How do I change the color of bar chart based on value?
In this example, we’re going to answer one the reader’s question, which is how to change the color of the bars in a bar chart based on the value i.e How do I change the color of my bar chart based on value? So let’s start and explore how to do.
we’re going to put a color based on the condition i.e if value is greater then equal to 50 then red else it will be green.
<!DOCTYPE html>
<html>
<head>
<title>Set Different Color For Each Bar based on value Using chart.js</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
</head>
<body>
<div style="margin-left:5%;margin-right:5%">
<canvas id="BarchatCanvas" style="width:80%"></canvas>
</div>
<script>
var BarchartData = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"June",
"July",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
datasets: [
{
label: "Projected sales",
backgroundColor: color => {
if (color.raw >= 50) {
return "green";
}
else {
return "red";
}
},
borderWidth: 1,
data: [42, 56, 9, 52, 66, 87, 51, 42, 32, 88,150,125]
}
]
};
const config = {
type: 'bar',
data: BarchartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
},
title: {
display: true,
text: "Bar Chart with Diffrent Color"
}
};
window.onload = function () {
new Chart("BarchatCanvas", config);
};
</script>
</body>
</html>
The post [Simple Trick]-Set Different Color For Each Bar in a Bar Chart in ChartJS appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Polyglot Language Switcher asp.net
- Uploading Image with other information with ajax, jquery and PHP
- Laravel send value from table row to controller
- Loading image is showing all server side request as well as client side request in ASP.NET
- Simulating mouseover event in Safari and Chrome
- HTML/PHP Removing part of a html input
- Navigation bar disappearing below mobile screen width
- Ajax get select tag id for passing through ajax
- Change height of div
- Anythingslider Panel change another object
- How to fix summernote is not a function?
- jQuery $.post() + IE8
- Conditional query from html controls
- A blank Option automatically append in select box
- jQuery - How to find the src of next image element
- Move div/blocks vertically with animations
- Jquery slideToggle "bounces" multiple times on resize
- Using Constructor and Invoking function
- Jumpy scrolling in Firefox in jQuery slimScroll 1.3.3 plugin
- jQuery validation plugin - not setting focus in Webkit browsers
- ajax post data doesn't return match value
- HTML5 form validation without submit button
- JQuery partial postback for dynamic control doesn't work
- d3.js selection based on id
- Change button state
- force the first 5 rows in a table to show with jquery
- jquery checkbox build an array containing a list of changed checkbox with the id
- Laravel POST Token missmatch exception (file upload)
- Getting data from dynamic form - multi-field row
- NiceScroll.js Resizing not working
- how to replace edited row in table
- jQuery Accordion - Don't want the entire parent li to be clikcable, just the link text
- Get the first html dropdown value using jquery to the text field
- Jquery contextMenu title and function on submenu
- Replace a few different elements in the string and return it
- Add another "Formats" select to TinyMce 4 in Wordpress
- How to include jquery in mean.io app
- Random net::ERR_CONNECTION_RESET issues
- Resize image with jQuery
- Why does jQuery store an element as a function?
- Attaching to click event (with jQuery) on submit button kills submission function
- Why doesn't table resize work here? jsfiddle url inserted
- Update localstorage object value & save it using jquery
- How to access the data from a jquery post in php?
- Trigger event not working inside Ajax Magnific popup
- How to parsing a image with user page id without submit button by jquery from
- Changing button label from c# code-behind
- add custom columns in kendo scheduler insted of one default column for day view
- Datatables for mutiple tables on one page having different td count each
- Table Row Click, External loading
- Problem accessing delicious api with ajax
- Accordion checklist counter document.form[]
- Google Places API - Uncaught SyntaxError: Unexpected token :
- jquery Slider not working on firefox however it is working on chrome
- Why does my "Back to Top" button fail on Firefox?
- Spring boot Thymeleaf populate dropdown list based on other dropdown list selections
- How to remove a null element in jquery?
- Checked radio buttons not working right in jQuery modal dialog
- jQuery Show/Hide - add / remove .active class
- Sending file in AJAX response in spring MVC
- fresh eyes please - theme issues - jquery / select
- ChartJS set default axis
- disable the submit button after it clicked once
- JQuery Datepicker not working in IE, Works fine with Firefox and Chrome
- Coda-Slider Problem in ie7, need to remove horizontal scrollbar
- Trying turn this jQuery slideShow plugin into a neat and modular "module"
- Javascript to change text of a span within div
- How to customise Kendo Scheduler Week View?
- zend, remove require=true from jquery
- jQuery detach() and remove() both not working on appended element
- How can I perform calculation in Javascript
- Ajaxify link so that it still accesses address on click but doesn't change page
- Flat UI Checkbox style not applying on startup
- jQueryUI dialog, is it possible to use your own buttons instead the one generated by dialog?
- HTML5 Video Play on Hover
- Django Make Button Ajax
- jQuery autocomplete menu click image to post data to express server
- Why are attributes being removed from an iframe on click?
- Passing a value to extjs textfield using jquery
- Javascript to jquery Ajax request
- Source property in event object cause rendering to fail
- Change Python Post Request to Ajax Post Request
- scroll a div automatically when a child is at the top / bottom borders
- Javascript - Convert dom element reference to node
- jquery and php - setting display date
- Calculate Business Days Jquery
- jQuery mobile styles are not getting applied over dynamically loaded content
- Google Places API - Details
- AmChart : hide event
- Toggle class on mouse click event
- How to change text from documents using jQuery?
- Show Large Image in another DIV on Rollover of Thumb
- How do I stilize an input type range using html video
- Jquery how to synchronizely compute total when user filtered the table
- Simple modal JSON Jquery
- How to sort automatically a JQuery draggable box by item's data-attribute
- always get $_FILE empy when trying to upload file with ajax and php?
- Fire ajax call on onclick and div
- gmaps-autocomplete-rails write Lang + Long written to hidden field
- Canceled Bootstrap modal still triggers canceled action when reopened (with class)
- JQuery Manipulate Children of Div Set
- Infinite Scroll, callback jquery function
- Dynamically autosize DIV on resolution change
- d3 js bidirectional horizontal bar chart
- Laravel Form call javascript function
- How to compare 2 values with client-side validation in ASP.NET MVC?
- Only one jquery function for different audio files on hover
- How do I get one jquery datepicker input to integrate with value of another?
- Using Jquery or Javascript to find unlabled html
- Appending form which has delete action to a laravel blade file using javascript
- Animate line in desired direction with Vivus.js
- Can't install jQuery File Upload in expressjs
- How to hide or remove placeholder using jquery placeholder.js
- php with curl sms sending with on live server
- Eloquent way to filter by average of 2 columns
- Colorbox doesn't open on second click
- jquery image replacement on screen size adjustment
- Can't Get jquery AJAX request to process
- Hide Scroll to Top Button for mobile
- Plugin not working as intended, possible Javascript / jQuery variable scope issue
- Change href to anchor on same page
- jQuery Flexigrid Resize columns in IE7 broken
- How to use data-toggle in a form action or window.location(PHP)?
- How can I display different success / error PHP messages using AJAX
- jQuery not loading in webview in Electron app
- How to hide element based on input value with javascript?
- jquery registration form, email if statement not working
- javascript for loop construct ordered list with colored circled on the numbers
- Stop firefox from exiting execution of deferred objects
- Microsoft JScript runtime error: '$' is undefined jquery reference error
- Toggle two containers with one click
- Rails dynamic form remote true controller not responding
- jQuery - moving an element of a list item inside another element of the same item + do this for each item of my list
- Scroll the div , when the fabric object is moved with in the canvas
- jQuery created class inside script
- Display Bootstrap Modal using javascript onClick
- Nested routes: How to query Rails DB and store values in JavaScript variables?
- Adding mask in jqGrid colum on editing line
- 400 Bad Request error with HTTP multipart request
- jquery addClass not working: "property or method addClass not supported"
- Showing and Hiding Select Elements Kills Chrome
- Trying to display related products using a specific product tag on Shopify
- Jquery ui autocomplete force user to pick answere
- jQuery.inArray(), returns -1 even if it contains the value in the array
- is this a valid id attributes ? if yes why can't javascript undersatand this
- display result from database based on checked checkbox
- Responsive Fotorama. How to responsive it to middle div?
- When background image hidden, no border in table
- Issue with image generator in html/javascript
- jQuery toggle cookie function