You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Chart.js柱状图代码高亮显示数值前三的柱子?

Highlight Top 3 Bars in Chart.js Bar Chart

Got it, let's adjust your existing code to highlight the top 3 highest-value bars instead of just the maximum one. Here's a straightforward way to do this:

Step 1: Replace the single-max index function with one that gets top N indices

Your original argMax only finds the index of the single largest value. We'll replace it with a function that returns the indices of the top N values in your dataset:

function getTopIndices(array, n) {
  // Create an array of objects with each value and its original index
  // Sort them in descending order of value, take the first N, then extract their indices
  return array
    .map((value, index) => ({ value, index }))
    .sort((a, b) => b.value - a.value)
    .slice(0, n)
    .map(item => item.index);
}

Step 2: Modify the color assignment logic

Instead of updating just one index, we'll iterate over the top 3 indices and set their highlight color:

Full Modified Code

function getTopIndices(array, n) {
  return array
    .map((value, index) => ({ value, index }))
    .sort((a, b) => b.value - a.value)
    .slice(0, n)
    .map(item => item.index);
}

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

// Set default color for all bars
var color = data.map(x => 'rgba(75,192,192,0.4)');

// Get indices of top 3 values
const top3Indices = getTopIndices(data, 3);

// Update color for top 3 bars
top3Indices.forEach(index => {
  color[index] = 'red'; 
  // Optional: Use different colors for each rank to make them distinct
  // if (index === top3Indices[0]) color[index] = '#ff0000';
  // else if (index === top3Indices[1]) color[index] = '#ff6666';
  // else color[index] = '#ff9999';
});

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

How It Works

  1. The getTopIndices function first maps your data array to include both each value and its original index.
  2. It sorts this array in descending order so the largest values come first.
  3. We slice the first 3 items and extract their original indices.
  4. Finally, we loop through these indices and update the corresponding positions in the color array to your highlight color.

You can tweak the highlight colors (like using different shades for 1st, 2nd, 3rd) by uncommenting the optional logic in the forEach loop.

内容的提问来源于stack exchange,提问作者Paphill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:07:30