简体   繁体   中英

Changing colors of single column in C3.js stacked bar chart

I am trying to highlight a single set of values in a c3.js stacked bar chart. Following this example I can change the color of a single bar in a non-stacked bar, but I can't figure out how to identify the indexes of a single stack. My JS is:

var chart = c3.generate({
  bindto: '#chart1',
  data: {
    x: 'x',
    columns: [
      ['x', "1ST", "2ND", "3RD", "4TH"],
      ['A', 6, 8, 2, 9],
      ['B', 3, 4, 1, 6],
      ['C', 4, 4, 2, 4]

    ],
    type: 'bar',
    groups: [
      ['A', 'B', 'C']
    ],
    colors: {
      A: '#666666',
      B: '#cccccc',
      C: '#428bca',
    },
    order: 'asc'
  },
  axis: {
    x: {
      type: 'category'
    }
  }
});

And the approach of the example is to do:

color: function (color, f) {
   return f.index === 4 ? "#dd0" : "#ddd";
}

Work in progress JSFIDDLE . How can I get the indexes of the 3 values of a single stack and then use them to change their colors? For example, if I want to highlight "2ND" by changing the colours to a set of reds?

Adapted from the example here --> http://c3js.org/samples/data_color.html

    color : function (color, d) {
        return d.index && d.index === 2 ? "#dd0" : color;
    },

https://jsfiddle.net/kmjpg30c/3/

d.index gives you the index of the stack - however, in your example there is no index 4 as the indexing starts at 0, so you have [0,1,2,3] as a possible range

So test against the index and return a new color if it matches and if it doesn't return the color that is originally passed in.

(the d.index test is present as the color function gets used by other routines that pass in just a string indicating the dataset ("A", "B", "C" in your example), so you need to test for the existence of the fields you need in d first.

if you want to highlight just one part of the stack use the .id field as well eg d.index === 2 && d.id === "A"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM