简体   繁体   中英

How can I show colorAxis color in Highcharts legend as series color?

I'm trying to show color coded pie chart using Highcharts. In the legend each series should have a color based on minColor and maxColor .

On first render this doesn't work (the legend has default colors like blue, black and green) and only after the redraw() event correct colors appear in the legend.

I'd like to avoid calling redraw() method manually as I have very many charts that get their data dynamically from external APIs, so doing it manually would increase my code complexity a bit too much.

Any ideas or suggestions?

You can see working example here: https://jsfiddle.net/p0cf392j/ (Resize your browser window to trigger the redraw() event and see the series colors change in the legend)

That problem is a Highcharts bug, which I already reported here: https://github.com/highcharts/highcharts/issues/12710

As a workaround, you can overwrite the translateColors method:

(function(H) {
    H.Series.prototype.translateColors = function() {
        var series = this,
            points = this.data.length ? this.data : this.points,
            nullColor = this.options.nullColor,
            colorAxis = this.colorAxis,
            colorKey = this.colorKey;

        points.forEach(function(point) {
            var value = point[colorKey],
                color;

            color = point.options.color ||
                (
                    point.isNull ?
                    nullColor :
                    (colorAxis && typeof value !== 'undefined') ?
                    colorAxis.toColor(value, point) :
                    point.color || series.color
                );

            if (color && point.color !== color) {
                point.color = color;

                if (series.options.legendType === 'point') {
                    series.chart.legend.colorizeItem(point, point.visible);
                }
            }
        });
    }
}(Highcharts));

Live demo: https://jsfiddle.net/BlackLabel/ht0nwvxj/

Docs: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

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