'Echarts multicolored line chart
Is it possible to make echarts line chart with 1 line painted in different colors? For example if value <= 0 the color is red, if > 0 the color is green?
Solution 1:[1]
Echarts has an option called visualMap
that does exactly what you are looking for.
- visualMap doc
- visualMap code example (I selected the example that fits best, but there are others)
In your case you'll have something like that :
visualMap: {
show: false, // Wether to show the legend or not (default: true)
pieces: [
{
min: -9999, // Normally not needed but doesn't work without that (1)
max: 0,
color: '#F35E07' // Red
},
{
min: 0,
color: '#93CE07' // Green
},
],
outOfRange: {
color: '#F35E07'
}
},
It'll split your line in 2 pieces :
- below 0 (written
max: 0
) : red - above 0 (written
min: 0
) : green
In addition, the visualMap
option has more to offer : you can have more than 2 pieces (like in this example), have a smooth gradient instead of pieces (using type: 'continuous'
like in this example), and many other things that are explained in its doc.
(1) Note about the bug: Normally if you don't specify
min
ormax
, it's set to-Infinity
orInfinity
. But here you have to specifymin
ANDmax
in one of the two pieces (I don't know why).
Solution 2:[2]
If you consider plotting two charts and ignoring some of its points with '-'
, you can achieve the same visual result of a multicolored line chart.
Although the documentation does not provide an immediate example of how to color specific segments of a line chart, it actually instructs about how you can use empty data,
While there are empty elements, the lines chart will ignore that point without passing through it----empty elements will not be connected by the points next. In ECharts, we use
'-'
to represent null data, It is applicable for data in other series.
With that in mind, by overlaying two equal charts and emptying some points, you can actually construct the logic of a multicolored chart. Notice that it is better if you can do it programmatically so that you can vary the number of line segments to be colored.
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;
option = {
xAxis: {},
yAxis: {},
series: [
{
data: [
[-20, -20],
[-10, 30],
[0, 40],
['-', '-'],
['-', '-']
],
type: 'line',
lineStyle: {
color: "red"
}
},
{
data: [
['-', '-'],
['-', '-'],
[0, 40],
[10, 100],
[20, 60]
],
type: 'line',
lineStyle: {
color: "green"
}
}
]
};
option && myChart.setOption(option);
.as-console-wrapper { max-heght: 100% !important }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.js"></script>
<body>
<div id="main" style="width: 225px;height:225px;"></div>
</body>
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 | |
Solution 2 | testing_22 |