Javascript highcharts:动态定义饼图中的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13875315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:00:48  来源:igfitidea点击:

highcharts: dynamically define colors in pie chart

javascriptcolorshighchartsseries

提问by dllhell

I'm trying to dynamically define color for each seria depending of their type. Below is my code which doesn't work but showing what I'm trying to do. I would like to define colour for certain type eg:

我试图根据它们的类型为每个系列动态定义颜色。下面是我的代码,它不起作用,但显示了我正在尝试做的事情。我想为某些类型定义颜色,例如:

if type = 'IS' then color =  '#FFCACA'

I cannot expect that ret will have all types so I need to know which types are returned in ret and then asociate color to certain type.

我不能期望 ret 将具有所有类型,因此我需要知道 ret 中返回哪些类型,然后将颜色与某些类型相关联。

How to do that?

怎么做?

this is code since data received:

这是自收到数据以来的代码:

success: function (ret) {


    $(function () {
        var chart;
        $(document).ready(function () {
            chart = new Highcharts.Chart({
                chart: {
                    renderTo: 'divPie_' + id,
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: true,
                    width: 350,
                    height: 350
                },
                title: {
                    text: refrigname
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage}%</b>',
                    percentageDecimals: 1
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Current selection',
                    color: (function () {
                            switch (ret.type) {
                                case 'AB': return '#C6F9D2'; 
                                case 'BC': return '#CCCCB3'; 
                                case 'CL': return '#CECEFF'; 
                                case 'CI': return '#FFCAFF'; 
                                case 'HB': return '#D0CCCD'; 
                                case 'ON': return '#FFCC99'; 
                                case 'PM': return '#FFCBB9'; 
                                case 'SR': return '#EAEC93'; 
                                case 'TS': return '#D7FBE6'; 
                                case 'IS': return '#FFCACA'; 
                                case 'FREE': return '#00FF00'; 
                            }
                    }),
                    data: (function () {
                        var arr = [];
                        $(ret).each(function () {
                            var labelname = "";
                            switch (this.type) {
                                case "AB": labelname = "Antibodies"; break;
                                case "BC": labelname = "Bacteria"; break;
                                case "CL": labelname = "Cell lines"; break;
                                case "CI": labelname = "Custom items"; break;
                                case "HB": labelname = "Hybridoma"; break;
                                case "ON": labelname = "Oligonucleotides"; break;
                                case "PM": labelname = "Plasmids"; break;
                                case "SR": labelname = "siRNA"; break;
                                case "TS": labelname = "Tissue samples"; break;
                                case "IS": labelname = "Isolates"; break;
                                case "FREE": labelname = "Free space"; break;
                            }
                            arr.push([labelname, this.cnt]);
                        })
                        return arr;
                    })()
                }]
            });
        });
    });


}

回答by Ricardo Alvaro Lohmann

For a pie chart you have to set the slice color inside data.
And you have to use the point nameand not serie type, serie type will always be "pie".

对于饼图,您必须在里面设置切片颜色data
而且您必须使用点name而不是意甲类型,意甲类型将始终是"pie".

For this you can use javascript object notationto store which color each serie will have.
It's fastar than use a switch.

为此,您可以使用 javascript 对象表示法来存储每个系列将具有的颜色。
它比使用switch.

var getColor = {
    'AB': '#C6F9D2',
    'BC': '#CCCCB3',
    'CL': '#CECEFF', 
    'CI': '#FFCAFF', 
    'HB': '#D0CCCD', 
    'ON': '#FFCC99', 
    'PM': '#FFCBB9', 
    'SR': '#EAEC93', 
    'TS': '#D7FBE6', 
    'IS': '#FFCACA', 
    'FREE': '#00FF00'
};

series: [{
    type: 'pie',
    name: 'Current selection',
    data: [
        {
            name: 'AB',
            y: 45.0,
            color: getColor['AB']
        }, {
            name: 'BC',
            y: 26.8,
            color: getColor['BC']
        }, {
            name: 'CL',
            y: 12.8,
            sliced: true,
            selected: true,
            color: getColor['CL']
        }, {
            name: 'CI',
            y: 8.5,
            color: getColor['CI']
        }, {
            name: 'HB',
            y: 6.2,
            color: getColor['HB']
        }, {
            name: 'ON',
            y: 0.7,
            color: getColor['ON']
        }
    ]
}]

You can see it working here.

你可以看到它在这里工作

回答by Jamie Wong

The returnstatement you have there is returning from the function being passed to the eachfunction, not the color function. Also, there's no need to use a switch case for this in JavaScript.

return您在那里的语句是从传递给each函数的函数返回的,而不是颜色函数。此外,在 JavaScript 中不需要为此使用 switch case。

EDIT: Try something like this

编辑:尝试这样的事情

series: [{
    type: 'pie',
    name: 'Current selection',
    color: {
        'AB': '#C6F9D2',
        'BC': '#CCCCB3',
        'CL': '#CECEFF',
        'CI': '#FFCAFF',
        'HB': '#D0CCCD',
        'ON': '#FFCC99',
        'PM': '#FFCBB9',
        'SR': '#EAEC93',
        'TS': '#D7FBE6',
        'IS': '#FFCACA',
        'FREE': '#00FF00'
    }[this.type]
}]

It's not really clear from your code what retis, so I'm not sure the above code works, but it should give you a rough idea of how it can be done.

从您的代码中并不清楚ret是什么,所以我不确定上面的代码是否有效,但它应该让您大致了解如何完成。

回答by wergeld

Why not set the color property when you push the data series to the chart? Without seeing what you are using to build your series object I can only provide some psuedo-code:

将数据系列推送到图表时,为什么不设置颜色属性?没有看到您用于构建系列对象的内容,我只能提供一些伪代码:

for each seriesItem in seriesList (
     set highcharts.series[seriesItem].name = seriesList[seriesItem].seriesTitle
     set highcharts.series[seriesItem].data = seriesList[seriesItem].data
     set highcharts.series[seriesItem].Note = seriesList[seriesItem].extraInfo
     set highcharts.series[seriesItem].color = switch (seriesList[seriesItem].type) {
                                case 'AB': return '#C6F9D2'; 
                                case 'BC': return '#CCCCB3'; 
                                case 'CL': return '#CECEFF'; 
                                case 'CI': return '#FFCAFF'; 
                                case 'HB': return '#D0CCCD'; 
                                case 'ON': return '#FFCC99'; 
                                case 'PM': return '#FFCBB9'; 
                                case 'SR': return '#EAEC93'; 
                                case 'TS': return '#D7FBE6'; 
                                case 'IS': return '#FFCACA'; 
                                case 'FREE': return '#00FF00'; 
                            }
     )

Essentially you preprocess the data series elements. See thisquestion for explicit formatting. You can set the colorproperty of a series - you do not have to depend on the default HighCharts color list or a custom color list as described in another answer. Note that the colorproperty is not listed in the HighCharts API referencebut you can use it.

本质上,您对数据系列元素进行了预处理。有关显式格式,请参阅问题。您可以设置color系列的属性 - 您不必依赖默认的 HighCharts 颜色列表或另一个答案中所述的自定义颜色列表。请注意,该color属性未在 HighCharts API参考中列出,但您可以使用它。

回答by Arif

I use Highcharts without giving any color property as it is using their own library for auto select color. Use below, hope it will work for u

我使用 Highcharts 没有给出任何颜色属性,因为它使用自己的库来自动选择颜色。在下面使用,希望它对你有用

series: [{
type: 'pie',
name: 'Current selection',
data: [
       ['Name_1',  537],
       ['Name_2',  181],
       ['Name_3',  156]
]
}]

we can set highchart custom color by setOption function

我们可以通过设置highchart自定义颜色 setOption function

Highcharts.setOptions({
  colors: ['#F64A16', '#0ECDFD', '#FFF000']
});