Guide to modifying the column color in Chart.js

Link to my codepen project: Check it out here

let ctx = document.getElementById('myChart').getContext('2d');
let chart = new Chart(ctx, {
  // Type of chart being created
  type: 'bar',

  // Data for the dataset
  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, 35, 2, -19, 30, 15]
    }]
  },

  // Configuration options go here
  options: {}
});
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceada6afbcbae0a4bd8efce0f6e0fe">[email protected]</a>"></script>

I would like to change the color of a column when its value is 0 and adjust its position. Thank you.

The desired result looks like this: https://i.sstatic.net/MiFZN.png

Answer №1

I believe I have resolved your issue:

function modifyChart(chart){
    let val = 2;
    let updatedValues = [];
    chart.data.datasets[0].data.forEach((e,i)=>{
    if(e===0){
      updatedValues.push('green');
      chart.data.datasets[0].data[i] = val;
      chart.data.datasets.push({data:
        Array.from({length:chart.data.datasets[0].data.length},function(el,j){
            if(i===j) return -val
        })})
    } else {
        updatedValues.push(chart.data.datasets[0].backgroundColor)
    }

  })
  chart.data.datasets.forEach(e=>{
    e.backgroundColor = updatedValues;
  })

  chart.update()
}

Try it out for yourself on this fiddle link: https://jsfiddle.net/7Lbjmw6r/

Answer №2

Hey there! To set the background color for each dataset in a chart, you need to provide an array of colors within the backgroundColor parameter. Take a look at this example:

var labels = ["A", "B", "C", "D", "E", "F", "G"];
var data = [35, 45, 60, 70, 55, 40, 30];
var background_colors = [];
for (var i = 0; i < labels.length; i++) {
   background_colors.push(getRandomColor());
}

var barChartData = {
  labels: labels,
  datasets: [{
    label: "My Data",
    fill: true,
    borderColor: "rgba(255,99,132,1)",
    backgroundColor: background_colors,
    data: data
  }]
};

Give it a try and let me know if it works for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Horizontal Panning Feature for D3 Horizontal Bar Charts

I am working on a D3 Bar Chart and I would like it to have horizontal panning functionality similar to this example: https://jsfiddle.net/Cayman/vpn8mz4g/1/. However, I am facing an overflow issue on the left side that I need to resolve. Below is the CSV ...

What is the best way to determine if two external values are equal within a mongodb criteria object?

Consider the following collection: {id: 1, name:"abc"}, {id: 2, name:null} When testing a property, I typically use this method: db.collecton.find({name:"abc"}, {name:1}); // This will return the first document. Now, I want to incorporate two external ...

Phantom.js WebDriver.io Error: Issue with Syntax - DOM Exception 12

Currently conducting tests using webdriver.io and phantom.js. The first test works successfully, providing a list of elements: return client .url(config.host) .waitForVisible('#myvenuelist', 2000) .click('#myvenuelist') ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

Unit testing in Typescript often involves the practice of mocking

One challenge with mocking in Typescript arises when dealing with complex objects, as is the case with any strongly-typed language. Sometimes additional elements need to be mocked just to ensure code compilation, such as using AutoFixture in C#. In contras ...

Retrieving the value of the option that has been selected from a dropdown

I have successfully implemented a drop-down menu with the following code: // Creating a select element for priority within a form in the bottom row div const formPriority = document.createElement("select"); formPriority.setAttribute("name","project"); form ...

JavaScript tabs function malfunctioning upon page load

I attempted to implement tabs on my website using this example: http://www.w3schools.com/howto/howto_js_tabs.asp Although everything is functioning correctly, the default tab isn't opening as expected. The tab opens, but the header color does not get ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

What is the threading model utilized by node.js?

Upon establishing a connection with a server operating on node.js, how is the connection handled? Is it one connection per process? Does it follow a connection per thread model? Or does it operate based on request per thread? Alternatively, does it use ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Launching an image link within the same location on the subsequent page to which it is directed

I'm completely new to creating websites so I may not be using the correct terminology. I've searched with various terms and ideas but haven't found any solutions to help me ask my question effectively or find examples of what I'm lookin ...

Displaying Image Previews in Rails View Using JavaScript

I am working on a functionality where I have a text_field that contains the URL of an image. The goal is to load this URL into an img tag and update the preview image when the user changes the URL in the text field. Below is the relevant erb code for the ...

Having trouble executing javascript with Ext.Ajax in Sencha-Touch2?

Currently, I am utilizing htmlPanel.js in Sencha-Touch as discussed in the Forum here to exhibit local HTML content. Even though I can load the HTML content with standard HTML tags, I'm facing issues with loading JavaScript. Here's the snippet o ...

Setting the height of a div tag in CSS/HTML5 to match the current height of the browser window

Is there a way to make the height of my div tag always equal to the height of the browser's window, so it adjusts automatically when the browser is resized? I have tried using .class { height: 100%; } But this doesn't work. I've learne ...