The proportions of the slices in a pie chart remain consistent even as the data is updated (based on the current version at the time of

I am currently experiencing an issue with a pie chart that is generated using the Google JSON schema for charts. The data for the chart is retrieved via ajax and loaded successfully, with all slices displaying correctly based on the initial values provided.

Sample Pie Chart Data

For instance, upon the initial load of the chart, there are four data elements that contribute to four distinct slices:

A = 410
B = 420
C = 900
D = 540

410 + 420 + 900 + 540 = 2270

410/2270 = 0.1806167400881057 = 65.02°
420/2270 = 0.1850220264317181 = 66.61°
900/2270 = 0.3964757709251101 = 142.73°
540/2270 = 0.2378854625550661 = 85.64°

However, the problem arises when the data for the pie chart is updated. Despite changes in the data values, the slice degrees remain constant, resulting in inaccurate visualization of the new data:

Updated Example Data

If the data transitions From: 410 + 420 + 900 + 540 = 2270 To: 410 + 420 + 9 + 540 = 1379

410/1379 = 0.2973168963016679 = 107.03°
420/1379 = 0.3045685279187817 = 109.65°
  9/1379 = 0.0065264684554025 = 2.35°
540/1379 = 0.3915881073241479 = 140.97°

In this scenario, despite a significant percentage change in one of the data values (from 900 to 9), the corresponding slice fails to reflect the degree variation. This discrepancy persists even after comparing the json data before and after the update, suggesting no apparent reason for the lack of synchronization between the data and the visual representation of the slices on the pie chart.

The only time the segmentation sizes adjust is when expanding a particular slice for further details; however, even then, the underlying issue remains unsolved. I have meticulously reviewed both the json structure and the process of drawing the chart but have yet to identify the root cause of this anomaly.

JSON Data

{ "cols":[{"id":"","label":"Title","pattern":"","type":"string"},{"id":"","label":"Dollars","pattern":"","type":"number"},{"id":"","label":"","pattern":"","type":"string","p":{"role":"style"}}],
  "rows":[{"c":[{"v":"A","f":"label a"},{"v":410.0,"f":"$410.00"},{"v":"fill-color: #00805D","f":null}]},
          {"c":[{"v":"B","f":"label b"},{"v":420.0,"f":"$420.00"},{"v":"fill-color: #00805D","f":null}]},
          {"c":[{"v":"C","f":"label c"},{"v":900.00,"f":"$900.00"},{"v":"fill-color: #78EAD3","f":null}]},
          {"c":[{"v":"D","f":"label d"},{"v":540.00,"f":"$540.00"},{"v":"fill-color: #F88451","f":null}]}]}

https://i.sstatic.net/u8mPP.png

<div id="chart_div"></div>

function drawPieChart(data) {

    $('#chart_div').empty();
    $('#chart_div').css('cursor','default')

    var options = chartOptions();

    var v_savings_suffix="";
    if(paoDetails.chart.mode.state === "sav") {
        v_savings_suffix = " (Savings)";
    }

    var _options = {
        title: v_chart_title + ' ' + v_savings_suffix
    }
    Object.assign( options, _options );

    var wrapper = new google.visualization.ChartWrapper({
        chartType: 'PieChart',
        dataTable: data,
        options: options,
        containerId: 'chart_div'
    });

    // Must wait for the ready event in order to
    // request the chart and subscribe to 'onmouseover'.
    google.visualization.events.addListener(wrapper, 'ready', onReady);

    function onReady() {
        google.visualization.events.addOneTimeListener(wrapper.getChart(), 'select', selectHandler);
        }
        wrapper.draw();

    function selectHandler() {

        var options=null;
        var selectedSlice = wrapper.getChart().getSelection()[0];
        if (selectedSlice) {    

            // get fund code from selected slice
            var fundCode = wrapper.getDataTable().getValue(selectedSlice.row, 0);
                if(fundCode !== "NAV") {
                options = wrapper.getOptions();
                if(options.slices) {
                    paoDetails.chart.mode.breakdown.fundKey = fundCode;                     
                    var slice = options.slices;
                    var keys = Object.keys(slice).map(Number);
                    if(keys) {      
                        paoDetails.chart.mode.breakdown.show = !paoDetails.chart.mode.breakdown.show;
                        paoDetails.chart.mode.funds = !paoDetails.chart.mode.funds;
                        recalcExemp();
                    }
                    wrapper.setOptions(options);
                    wrapper.draw();          
                }
            }
        }
    }
} // end drawPieChart

Answer №1

The problem with the root pie slice persists and remains unsolved. While this may not be entirely a bug within the Google pie chart, my experimentation with the data only leads me to believe that somehow the pie chart needs to be refreshed. I am considering options to reset percentages in the pie chart with each data update. One approach I am exploring is calling the data load function twice - setting the percentages to 0 on the first call and then loading the actual data on the second call. It may not be the most elegant solution, but it could potentially resolve this issue. Any assistance or guidance on this matter would be greatly appreciated.

I have observed that the percentages of the pie slices remain unchanged even when the underlying data for the pie chart is modified.

https://i.sstatic.net/MvJHX.png

Interestingly, I found that the percentage of the green pie slice only updated when I manipulated the variable value during a debugging session. This inconsistency suggests that the pie chart percentages are not dynamically updating despite changes in the total data value.

For reference, the chart container is nested within a Bootstrap column and the JavaScript literal data for the chart is generated from PHP.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Faces in ThreeJS Object Group lack shadows

I'm encountering an issue where shadows aren't being received on the faces within an Object3D group. Although the shadows are cast from the objects and received by the ground, they don't interact with each other as expected. I've look ...

Having trouble loading JSON data in your ExtJS Tabpanel?

I have a tabpanel set up with two panels, and I am fetching data via JSON. The data retrieval works perfectly in the first tabpanel, but I'm facing issues parsing the JSON data in the second tabpanel. Any suggestions on how to approach this? var regi ...

Transforming a three-dimensional array into a two-dimensional array using JavaScript

I need help transforming a 3D array into a 2D array with specific dimensions. The current structure of my data is as follows: [ [[0,0,345], [1,0,555], ... [9,0,333]], ... [[0,9,1000], [1,9,987], ... [9,9,129]] ] The goal is to convert it into this format: ...

The stunning fade effect of Magnific Popup enhances the visual appeal of the inline gallery

I'm currently using magnific popup for an inline gallery, but I'm not seeing any effects. I would like to have a fade effect when opening/closing the popup. Can someone assist me with achieving this? https://jsfiddle.net/gbp31r8n/3/ [Check o ...

Can you explain the meaning of the code snippet i = (i + 1 == count) ? 0 : i + 1;?

I recently utilized this particular line of code in my jQuery plugin, but I find myself struggling to fully grasp its functionality. Below is a snippet of the plugin's code: Could someone provide me with an explanation? (function ($) { $.simpleS ...

Tips for updating a value within ng-repeat only if the value is equal to "string"; otherwise, hide it from display

I'm having trouble updating the data in my table to display "Yup" or blank space based on certain conditions. I am new to this and tried a solution, but it's not working: {{ person.value ? "Yup":" "}} .. Can anyone help me with this? angular.m ...

Retrieving a Collection of Items Generated in the Past Day from a Specific Dataset Using JavaScript

I have been tasked with extracting a specific set of arrays from given data based on a 24-hour time frame using the timestamps provided. I initially attempted the code below, but unfortunately, it kept returning the same data to me. I suspect there may be ...

Guide to Spidermonkey Bytecode Documentation

I've been searching for a comprehensive guide to spidermonkey's bytecodes for some time now, or at least something that gives me an overview of their purpose. Does anyone know of a good resource for this? Thank you! ...

I'm having trouble understanding why this code is causing confusion for the user's selection during a specific part of the execution. I can't seem

In this memory game, event listeners respond to user input after a sequence of colored divs change color to appear illuminated. The expected behavior is that once the user clicks on the correct div in the right order, the sequence restarts with an additi ...

Tips for dynamically inserting a new column into a table at any position other than the beginning or end

I have created a dynamic table where rows and columns can be added dynamically. However, I am facing an issue where I am unable to add a new column between the first and last column of the table. Currently, new columns are only being added at the end. $ ...

Converting AngularJS scope objects into plain JavaScript arrays: a comprehensive guide

What is the best way to convert an AngularJS scope object into a simple JS array? I have a function that checks if any checkbox is checked and adds the corresponding value to an object. Now, I am trying to transfer the object values to an array and alert ...

Change CSS style sheets depending on the size of the viewport

I've tried to implement the method from CSS-Tricks that allows for changing stylesheets based on the viewport width using multiple .css files and jQuery. However, my code isn't functioning as expected. I've spent the past hour trying to figu ...

Converting a Javascript array to an NSArray in Xcode

As a complete beginner to Xcode and programming in general, I recently built an app using javascript and html and integrated it into Xcode. Currently, my main focus is on extracting multiple arrays from the html/javascript file and exporting them as a csv ...

Update the color of buttons after being clicked - Bootstrap

If I want to change the class "btn-success" to "btn-warning" or update the color code to "#ffc107" upon a successful process, how can I achieve that? Button ; <button type="submit" name="teklifver" value="Teklif Ver" class="btn btn-block btn-success" ...

Comparing arrays with objects containing different sequences in JavaScript: A guide

I have two arrays where I need to identify matching values across different sequences. How can I achieve this comparison using plain JavaScript? Specifically, I am trying to match the values of property1 and name and then extract property3 when property1 m ...

In PHP/HTML, if the URL is domain.co.uk/?debug, then the following action will

Apologies for what may seem like a basic question, but I've been searching for a clear answer with no luck! My goal is simple - when someone goes to , I want to show extra details, like the code version or any other notes I include. Once again, sorr ...

Switching XML to JSON using React.js

Currently, I am in the process of developing an application with a requirement to retrieve data from a web API that provides XML responses. However, my objective is to obtain this information in JSON format, but unfortunately, the API does not offer suppor ...

Creating multiple carousels using a loop: Passing `$(this)` to Slick.js plugin

Is there a way to correctly pass $(this).find('.option') and $(this).find('.prev_next') to Slick.js? Currently, I am encountering the error message: Syntax error, unrecognized expression: [object Object]:not(.slick-cloned) in jquery-2.1 ...

Trouble with the find() function in jQuery not functioning properly upon page initialization

In my jQuery script, I am attempting to remove the style attribute from all table, tr, and td elements that are within a div element with an id="testdiv". $(document).ready(function(){ $("#testdiv").find("table, tr, td").removeAttr("style"); }); When ...

Customizing the appearance of charts in AngularJS using the Chart.js

I just started experimenting with AngularJS and recently created a horizontal bar chart using Chart.js and HTML. My next step is to make the chart dynamically appear on the page with the help of AngularJS. Can someone please provide some guidance on how I ...