'How override appearance of individual ECharts data points when using a dataset?
I have an echarts plot with many data points, which I am supplying using a dataset. How can I set formatting options for only some data points?
e.g. If I wasn't using a dataset then I might highlight a single data point like this:
series: [
{
type: 'bar',
data: [
97.7,
{
value: 43,
itemStyle: {
color: '#ff0000'
}
},
92.5
]
But using a dataset I have no place for this extra information:
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
dataset: {
source: [
['A', 97.7],
['B', 43],
['C', 92.5]
]
},
xAxis: { type: 'category' },
yAxis: {},
series: [{ type: 'bar' }]
});
If I try to set options in series[type='bar'].data
then it removes the data supplied by the dataset.
Solution 1:[1]
Facing the same issue and not believing that this functionality isn't implemented into ECharts. I found a solution by using a callback function.
By defining an object holding the colors for each data point at its respective key I am able to return the color defined:
<div id="main" style="width: 600px;height:400px;"></div>
var myChart = echarts.init(document.getElementById('main'));
let colors = {
'A': '#FF0000',
'B': '#00FF00',
'C': '#0000FF'
};
myChart.setOption({
dataset: [{
source: [
['name', 'value'],
['A', 97.7],
['B', 43],
['C', 92.5]
]
}],
xAxis: {
type: 'category',
},
yAxis: {},
series: {
type: 'bar',
itemStyle: {
color: function(seriesIndex) {
console.log(seriesIndex);
return (colors[seriesIndex.name]);
}
}
}
});
fiddle
Additionally I added an optional header row to the dataset. This is not necessary because ECharts is referencing the first column in the dataset by "name". For additional clarity I added a logging statement to the function so you can gain some insight on how the dataset is processed when the chart is rendered.
If a simpler solution is needed it is achievable by creating an array of colors and setting the colorBy option to "data" in the series object - see ECharts documentation.
This simply iterates through the list of colors and assigns them to each entry in the set:
<div id="main" style="width: 600px;height:400px;"></div>
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
dataset: [{
source: [
['name', 'value'],
['A', 97.7],
['B', 43],
['C', 92.5]
]
}],
xAxis: {
type: 'category',
},
color: [
'#FF0000',
'#00FF00',
'#0000FF'
],
yAxis: {},
series: {
type: 'bar',
colorBy: 'data',
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |