Custom Dynamic color for echarts

Viewed 7863

I am using echarts for my data visualization.... I got the solution for static data from here.. But in my case I have dynamic data and don't know how to make it work. The data items changes from time to time. It is not always 3 items like below. It could be any number.

var option = {
xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed']
},
yAxis: {
    type: 'value'
},
series: [{
    data: [
        {
            value: 120,
            itemStyle: {color: 'blue'},
        },
        {
            value: 200,
            itemStyle: {color: 'red'},
        },
        {
            value: 150,
            itemStyle: {color: 'green'},
        }
    ],
    type: 'bar'
}],
  graph: {
    color: colorPalette
  }
};

Someone have any idea about this.

Any help is appreciated. Thanks

2 Answers

You can have an array of colors predefined and randomly pop a color from that array, for each bar you have to draw:

var colors = [
  "blue",
  "red",
  "yellow",
  "green",
  "purple"
];

function popRandomColor(){
  var rand = Math.random();
  var color = colors[Math.floor(rand*colors.length)];
  colors.splice(Math.floor(rand*colors.length), 1);
  return color;
}

Then call popRandomColor() everytime you need a color from the color bank.

var option = {
xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed']
},
yAxis: {
    type: 'value'
},
series: [{
    data: [
        {
            value: 120,
            itemStyle: {color: popRandomColor()},
        },
        {
            value: 200,
            itemStyle: {color: popRandomColor()},
        },
        {
            value: 150,
            itemStyle: {color: popRandomColor()},
        }
    ],
    type: 'bar'
}],
  graph: {
    color: colorPalette
  }
};

Is dynamic data with different color you want? check below

// put any color you want in Array colors
var colors = [
    "blue",
    "red",
    "green"
];

// can be any length
var data = [{
    category: 'cate1',
    value: 120
}, {
    category: 'cate2',
    value: 200
}, {
    category: 'cate3',
    value: 150
}, {
    category: 'cate4',
    value: 135
}, {
    category: 'cate5',
    value: 54
}]

let category = [];

let seriesData = data.map((item, index) => {
    category.push(item.category);
    return {
        value: item.value,
        itemStyle: {
            color: colors[index % colors.length]
        }
    }
});

var option = {
    xAxis: {
        type: 'category',
        data: category
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: seriesData,
        type: 'bar'
    }]
};
Related