Change the color of a bar chart in chart.js depending on the value it represents

function findMaxIndexes(array, n) {
  const maxValues = array.slice().sort((a, b) => b - a).slice(0, n);
  return array.map((x, i) => [x, i]).filter(pair => maxValues.includes(pair[0])).map(pair => pair[1]);
}

// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString()); 

// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');

// change max color
findMaxIndexes(data, 3).forEach(index => color[index] = 'red');

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                    label: 'value',
                    data: data,
                    backgroundColor: color,
            }]
        }
});

Hey Everyone! I stumbled upon this interesting code snippet on Stack Overflow regarding Chart.js and changing the color of maximum value bars. However, I'm unsure how to modify it to highlight the top three values.

Could someone guide me on adjusting this code to display the three highest values in a distinct color?

Answer №1

When given an array containing various number values labeled "data," the task is to arrange them in a sorted array. Following this, you will need to map these values from the original data and assign a specific color based on their position within the sorted array.

const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

Below is a demonstration of how this can be implemented.

const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O'];
const data = labels.map(l => Math.floor(Math.random() * 1000) + 1);
const sortedData = data.slice().sort((a, b) => a - b);
const backgroundColors = data.map(v => sortedData.indexOf(v) >= data.length - 3 ? 'red' : 'green');

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: data,
      backgroundColor: backgroundColors
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

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

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

Modifying the nginx configuration file for an Angular application: a step-by-step guide

After deploying my Angular application on an nginx server, I encountered a problem. When I accessed http://**.8.100.248:30749, it displayed the default index.html page from the nginx server instead of my actual application located in the html folder under ...

Leveraging Discord.js to retrieve all messages sent while the bot was inactive

My plan is to create a bot that will store all messages sent in a channel into a txt file on my computer. However, the challenge is that since my computer is not always on when the bot is running, there are gaps in the stored messages in the .txt file. I a ...

Submit the scaled-down form image to the server

When attempting to upload a resized image to the server, an error stating "Required MultipartFile parameter 'file' is not present" occurs. Interestingly, this error only appears when trying to upload the resized image, as uploading the original f ...

How can you transform the outcome of a TYPO3 repository search into a JSON format?

Is it possible to convert the outcome of a "findAll()" function on a Repository into a JSON object, make changes to specific properties in JavaScript, and then send it back to the Action, converting it again for use by the Action to persist it in the datab ...

Received the error 'Headers cannot be set after they have been sent to the client' upon the second request

I created a web server that acts as a client-side application using socket.io-client and express. This setup is necessary for another project I am working on. The web server emits the posted string and responds by sending the served string when it receive ...

Help me find a way to refine div elements in the HTML response obtained via AJAX

Currently, I am working on creating a dynamic fields form that includes settings such as Label, Name, Id, Min, Max, and Value. Whenever I click on a button, a JavaScript function is triggered to return the definition of a text-box within two separate div ...

Tips for embedding a hyperlink in your HTML website

While I've mastered adding images to my HTML website, there's one thing that still eludes me despite scouring numerous online resources. I recently created a small animation using JavaScript on a different IDE, and I have the link to my output: ...

Using Angular: connecting $viewContentLoaded to manually initiate app bootstrapping

I have an Angular module that I am bootstrapping manually and attempting to access its $rootScope to add an event listener for $viewContentLoaded. Below is the code snippet: angular.bootstrap(el, [appname]); //////////////////////////// Fixing links cons ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

Unable to add a new key and value pair in Filter Function - issue persists

I have a filter function in my Node server that is structured like this let totalHours = 0; let laborCost = 0; const employees = await Employees.findOne({ company }); const timeCards = await TimeCard.find({ employee: employees.employees }).populate(&qu ...

What is preventing these AngularJS applications from functioning simultaneously?

I have a fully functioning AngularJS app that I developed as a standalone "CreateUser" widget. Now, I am working on creating a second widget called "ViewUsers," which will display a table of current users (with the intention of connecting them or keeping t ...

Verify whether the labels are blank, remain as they are, or transfer the data to the database

Currently, I am utilizing PHP, HTML5, and JavaScript for my project. The task at hand involves creating a webpage that will be connected to a database. However, I have encountered an issue wherein the page proceeds to the next step and sends data even when ...

What is the best way to display a loading animation until the entire wizard has finished loading in the jQuery-steps

I need help with implementing a loading animation using the jQuery-steps plugin in my wizard type form. I want the animation to be displayed until the entire wizard has loaded completely, but I'm unsure of how to enable this feature as there is a labe ...

Ways to customize the appearance of an iframe's content from a separate domain

I am facing a challenge with my widget and multiple websites. The widget is hosted on one domain, but the websites use an iframe to display it. Unfortunately, because of the Same Origin Policy, I cannot style the content of the iframe from the parent websi ...

Reorder elements in CSS Grid

I've been working with a css-grid and it's almost there, but I'm stuck on reordering the items in a specific way. Currently, the html layout is set as “1, 2, 3, 4,…10”, but for smaller screens, I want the visual order to be “1, 2, 4 ...

Enabling cross-origin resource sharing (CORS) can be tricky when server access is limited

I have been diligently investigating whether I can resolve the 'Access-Control-Allow-Origin' error that keeps popping up. When retrieving data from certain reports in CSV format, I am forced to use a Chrome plug-in that disables CORS. Even after ...

Activate a function after selecting a file using the input type=file and showcase the file path by utilizing ng-repeat

<input type="file" id="file" name="file" ng-show="attachFile" /> <button type="button" ng-model="attach" ng-click="add()">Attach</button> <div class="panel panel-default" ng-show="displayAttachments"> <div class="panel-h ...

Create a Promise that guarantees to reject with an error

I am relatively new to utilizing promises, as I typically rely on traditional callbacks. The code snippet below is from an Angular Service, but the framework doesn't play a significant role in this context. What really matters is how to generate a pro ...

creating an audio streaming application using child processes in nodejs

How can I effectively send a stream to a child process for streaming audio from a client to a server? I have successfully obtained the audio stream from a client. const ss = require('socket.io-stream'); const socketIo = require('socket.io& ...