jQuery UI Widgets Forums Chart Set colors based on Datafield Values

This topic contains 7 replies, has 4 voices, and was last updated by  yoda 10 years, 3 months ago.

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author

  • RainMan
    Participant

    Hi,
    I have a jqxChart (pie chart) that connects to a database via JSON.
    e.g.

    var source = {
    datatype: "json",
    datafields: [
                    {name: "foo"},
                    {name: "bar"},
                ],
    url: ".../blah/UrlSrc"
    };

    And my settings after creating a dataAdapter are :

    var settings = {
    source: dataAdapter,
    colorScheme: 'scheme02',
    seriesGroups: [{
    type: 'pie',
    showLabels: true,
    //..other settings
           series: [{
                  dataField: 'foo',
                  displayText: 'FOO'
             //...other settings
            }]
    }]
    }

    So basically the char is created on the dataField: Foo present in a table in my database.
    Now the column Foo in my table can have only 4 kind of values i.e. A, B, C, or D. (not necessary that all the values are present all the time.)
    My requirement is now to have an adapter/function of sorts that can read Foo while creating the pi chart and based on its values,
    assign colors.
    e.g. if Foo.value == A
    then color = red, etc.

    I did try to use ‘addColorScheme’ but that doesn’t allow me to assign colors to Field values.

    How do I achieve this?


    RainMan
    Participant

    “So basically the chart is created…”


    Dimitar
    Participant

    Hello RainMan,

    Here is an example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
        <script type="text/javascript" src="../../scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
        <script type="text/javascript" src="../../jqwidgets/jqxchart.js"></script>
        <script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                // prepare chart data as an array
                var source =
                {
                    datatype: "csv",
                    datafields: [
                        { name: 'Browser' },
                        { name: 'Share' }
                    ],
                    url: '../sampledata/desktop_browsers_share_dec2011.txt'
                };
    
                var dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, beforeLoadComplete: function (records) {
                    var colorsArray = new Array();
                    for (var i = 0; i < records.length; i++) {
                        switch (records[i].Share.trim()) {
                            case "5":
                                colorsArray.push("#ff0000");
                                break;
                            case "10":
                                colorsArray.push("#ffff00");
                                break;
                            case "20":
                                colorsArray.push("#00ff00");
                                break;
                            case "40":
                                colorsArray.push("#0000ff");
                                break;
                        };
                    };
    
                    $.jqx._jqxChart.prototype.colorSchemes.push({ name: 'myScheme', colors: colorsArray });
                }, loadError: function (xhr, status, error) { alert('Error loading "' + source.url + '" : ' + error); }
                });
    
                // prepare jqxChart settings
                var settings = {
                    title: "Desktop browsers share in Dec 2011",
                    description: "(source: wikipedia.org)",
                    enableAnimations: true,
                    showLegend: false,
                    legendPosition: { left: 520, top: 140, width: 100, height: 100 },
                    padding: { left: 5, top: 5, right: 5, bottom: 5 },
                    titlePadding: { left: 0, top: 0, right: 0, bottom: 10 },
                    source: dataAdapter,
                    colorScheme: 'myScheme',
                    seriesGroups:
                        [
                            {
                                type: 'pie',
                                showLabels: true,
                                series:
                                    [
                                        {
                                            dataField: 'Share',
                                            displayText: 'Browser',
                                            labelRadius: 100,
                                            initialAngle: 15,
                                            radius: 130,
                                            centerOffset: 0,
                                            formatSettings: { sufix: '%', decimalPlaces: 1 }
                                        }
                                    ]
                            }
                        ]
                };
    
                // setup the chart
                $('#jqxChart').jqxChart(settings);
    
            });
        </script>
    </head>
    <body class='default'>
        <div id='host' style="margin: 0 auto; width: 870px; height: 400px;">
            <div id='jqxChart' style="width: 850px; height: 400px; position: relative; left: 0px;
                top: 0px;">
            </div>
        </div>
    </body>
    </html>

    And here is the contents of the file desktop_browsers_share_dec2011.txt:

    Internet Explorer, 5
    Firefox, 20
    Chrome, 10
    Safari, 5
    Opera, 20
    Other, 40

    Best Regards,
    Dimitar

    jQWidgets team
    http://www.jqwidgets.com/

    Set colors based on Datafield Values #54345

    RainMan
    Participant

    Thanks a ton. Works like a charm. I just wanted to know one more thing…
    whats the meaning of
    $.jqx._jqxChart.prototype.colorSchemes.push({ name: 'myScheme', colors: colorsArray });

    I mean what does $.jqx._jqxChart.prototype signify?

    Set colors based on Datafield Values #54347

    Dimitar
    Participant

    Hi RainMan,

    This is an object prototype. For more information, you can refer to the following page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype.

    Best Regards,
    Dimitar

    jQWidgets team
    http://www.jqwidgets.com/


    zert
    Participant

    Hi Dimitar,

    I tried to adapt your code on my page but no success, the color scheme isn’t applied on the chart. The colorarry is well formatted : #5ade7b,#db3939,#ffb33b,#5ade7b,#ffb33b,#5ade7b but all columns are on #5ade7b color.

    Here is my code, am I missing something? :

    var source3 =
    {
    	datatype: "json",
    	datafields: [
    			 { name: 'Mois'},
    			 { name: 'Nombre'}
    		],
    		url: 'source.php?filtre=2'
    		};
    var dataAdapter = new $.jqx.dataAdapter(source3, { async: false, autoBind: true, beforeLoadComplete: function (records) {
    		var colorsArray = new Array();
    		for (var i = 0; i < records.length; i++) {
    			switch (true) {
    				case (records[i].Nombre <= 80):
    					colorsArray.push("#db3939");
    					break;
    				case (records[i].Nombre > 80 && records[i].Nombre < 90):
    					colorsArray.push("#ffb33b");
    					break;
    				case (records[i].Nombre >= 90):
    					colorsArray.push("#5ade7b");
    					break;
    					};
    				};
    				$.jqx._jqxChart.prototype.colorSchemes.push({ name: 'myScheme', colors: colorsArray });
    				}, loadError: function (xhr, status, error) { alert('Error loading "' + source.url + '" : ' + error); }
    			});
    var settings3 = {
                    title: "Sante du SI (%)",
                    description: "<?php echo $date;?>",
                    enableAnimations: true,
    				showLegend: false,
                    padding: { left: 10, top: 5, right: 20, bottom: 5 },
                    titlePadding: { left: 0, top: 0, right: 0, bottom: 10 },
                    source: dataAdapter,
    				showToolTips: false,
                    categoryAxis:
                        {
                            dataField: 'Mois',
                            flip: false,
    						textRotationAngle: 75,
                            horizontalTextAlignment: 'right',
                            verticalTextAlignment: 'top',
                            textRotationPoint: 'right',
                            textOffset: { x: -5, y: +5 }
                        },
                    colorScheme: 'myScheme',
                    seriesGroups:
                        [
                            {
                                type: 'column',
                                orientation: 'horizontal',
    							//mouseover: myEventHandler2Before,
    							//click: myEventHandler,
                                valueAxis:
                                {
                                    flip: true,
                                    displayValueAxis: false,
                                    description: '',
    								unitInterval: 1,
                                    minValue: 0
                                },
                                series: [
                                        { dataField: 'Nombre', showLabels: true }
                                    ]
                            }
                        ]
                };

    Dimitar
    Participant

    Hello zert,

    The previously suggested approach is not applicable for “column” type series. It will still create a new scheme, but will apply the first colour to the first series, the second colour to the second series, etc. In your case, the only series, “Nombre”, will get the first selected colour from the first call of the switch statement.

    Best Regards,
    Dimitar

    jQWidgets team
    http://www.jqwidgets.com/


    yoda
    Participant

    The most easy and flexible approach I found, and you can use it in any type of series, is this one:
    http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxchart/index.htm#demos/jqxchart/javascript_chart_series_conditional_colors.htm

    Basically you define your own color assignment function like this:

    colorFunction: function (value, itemIndex, series, group) {
    return (value < 10) ? ‘#FF0000’ : ‘#00FF00’;
    }

    I like this approach because it allows me to override the chart’s colors assignment and use my own colors in any way I want.
    The only thing you need to be careful with is to make sure that your function is fast because the chart will call it many times and for each data point.

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.