Creating a unique custom object for Highcharts series involves defining specific properties and methods that

I have a unique set of data to display in a Highcharts column stack chart. Please see the data and code below:

var customData = [
        {
            "personId": "ff6b9c90-3961-4995-b05c-eaa8c0689f7c",
            "pid": "PID-2",
            "averageCycleTime": 3.216666666666667,
            "idealCycleTime": 5,
            "cycleDetails": [
                {
                    "cycleId": "4019551e-b6b8-45cb-8df6-1c8c3c9d8995",
                    "visionCycleId": "1",
                    "cycleDuration": 4.433333333333334,
                    "actionDetails": null
                },
                ...
            ]
        },
        {
            ...
        }
    ]

Using the JavaScript snippet provided, I'm converting this data into Highcharts series format.

let sortedArray : any;
     sortedArray =  customData.sort((a : any,b : any)=> a.pid.localeCompare(b.pid));
let personIDList = sortedArray.map((pItems : any,idx : any)=> pItems.pid);
    const series = customJson.map((value, key) => {
      return {
        name: `Cycle-${key + 1}`,
        data: value.cycleDetails.map((v) => ({
          y: v.cycleDuration,
          videoId: v.cycleId,
        })),
      };
    });
    

In the above process, I organize the array based on PID for category setup. You can now review the chart configurations with the data provided.

{
        chart: {
          type: 'column'
        },
        title: false,
        xAxis: {
            categories: this.personIDList,
            labels :{
              style : {
                color : '#1e272e',
                cursor : 'pointer'
              }
            }
        },
        ...

The result of implementing the above code is shown in the provided link. However, the arrangement of bars seems shuffled as per PID. The desired outcome should align each PID's details within the same column, resembling the second image linked.

My anticipated data chart visualization would resemble the following:

https://i.sstatic.net/vMjQh.jpg

Answer №1

To achieve the desired outcome, begin by extracting all raw data from the input and organizing it into a nested object with primary keys labeled as visionCycleId and secondary keys as pid (referred to as rawData in the code snippet). Then, proceed to further process this data using the list of pids to create data arrays for chart representation:

data.sort((a, b) => a.pid.localeCompare(b.pid))

const personIDList = data.map(({ pid }) => pid);

// retrieve the data
const rawData = data.reduce((acc, { pid, cycleDetails }) => {
  cycleDetails.forEach(({ visionCycleId, cycleDuration }) => 
    acc[visionCycleId] = Object.assign(acc[visionCycleId] || {}, { [pid] : cycleDuration }))
  return acc
}, {})

const series = Object.entries(rawData)
  .map(([k, v]) => ({
    name: `Cycle-${k}`,
    data: personIDList.map(pid => v[pid] || 0)
  }))

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },
  plotOptions: {
    series: {
      stacking: 'normal'
    }
  },
  xAxis: {
    categories: personIDList
  },
  yAxis: {
    reversedStacks: false
  },
  accessibility: {
    enabled: false
  },
  series
});
<script src="https://code.highcharts.com/highcharts.js"></script><script type="text/javascript">
  var data = [{
      "personId": "ff6b9c90-3961-4995-b05c-eaa8c0689f7c",
      "pid": "PID-2",
      "averageCycleTime": 3.216666666666667,
      "idealCycleTime": 5,
      "cycleDetails": [{
          "cycleId": "4019551e-b6b8-45cb-8df6-1c8c3c9d8995",
          "visionCycleId": "1",
          "cycleDuration": 4.433333333333334,
          "actionDetails": null
        },
        {
          "cycleId": "de3203bc-9a82-4aaa-a448-ea83d51793e1",
          "visionCycleId": "2",
          "cycleDuration": 3.7333333333333334,
          "actionDetails": null
        },
        {
          "cycleId": "7418d534-4159-4f0c-8dbe-3271dcf16f24",
          "visionCycleId": "3",
          "cycleDuration": 3.7333333333333334,
          "actionDetails": null
        },
        {
          "cycleId": "066cc343-7924-4c9e-86df-f062f9987183",
          "visionCycleId": "0",
          "cycleDuration": 0.9666666666666667,
          "actionDetails": null
        }
      ]
    },
    {
      "personId": "6ce9ac4d-f32b-468e-809a-24ae51e00544",
      "pid": "PID-3",
      "averageCycleTime": 0.26666666666666666,
      "idealCycleTime": 5,
      "cycleDetails": [{
        "cycleId": "55aab433-b2d8-4e62-a40b-d6b15610fc37",
        "visionCycleId": "0",
        "cycleDuration": 0.26666666666666666,
        "actionDetails": null
      }]
    },
    {
      "personId": "d7a4362f-07f9-4e64-9ccb-be8d0a194c61",
      "pid": "PID-4",
      "averageCycleTime": 4.133333333333333,
      "idealCycleTime": 5,
      "cycleDetails": [{
          "cycleId": "c664f6ce-a1fd-4d44-96f6-0236181fd784",
          "visionCycleId": "1",
          "cycleDuration": 3.8333333333333335,
          "actionDetails": null
        },
        {
          "cycleId": "fc53a523-9d32-40ea-af3d-957122fb979e",
          "visionCycleId": "2",
          "cycleDuration": 3.8,
          "actionDetails": null
        },
        {
          "cycleId": "791666d3-b1f9-4bcf-ad13-8639bfd2ead9",
          "visionCycleId": "0",
          "cycleDuration": 4.766666666666667,
          "actionDetails": null
        }
      ]
    }
  ]
</script>
<div id="container"></div>

Answer №2

To implement the Highcharts series structure, you must follow these steps:

const sortedData = data.sort((a, b) => a.pid.localeCompare(b.pid));
const personIDs = sortedData.map((person, index) => person.pid);

const seriesData = [];

sortedData.forEach((person, personIndex) => {
    person.cycleDetails.sort((a, b) => a.visionCycleId.localeCompare(b.visionCycleId));
    person.cycleDetails.forEach((cycleDetail, cycleIndex) => {
        if (seriesData[cycleIndex]) {
            seriesData[cycleIndex].data.push([personIndex, cycleDetail.cycleDuration]);
        } else {
            seriesData.push({
                name: 'Cycle-' + cycleDetail.visionCycleId,
                data: [
                    [personIndex, cycleDetail.cycleDuration]
                ]
            });
        }
    });
});

Highcharts.chart('chartContainer', {
    chart: {
        type: 'column'
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    xAxis: {
        categories: personIDs
    },
    yAxis: {
        reversedStacks: false
    },
    series: seriesData
});

Check out a live demo here: http://jsfiddle.net/BlackLabel/2xqncjzw/

For more information, refer to the API Reference: https://api.highcharts.com/highcharts/yAxis.reversedStacks

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

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

What is the method for accessing extra parameters in the signIn() callback function in [...nextauth]?

As per the Next Auth documentation, it is possible to pass extra parameters to the /authorize endpoint using the third argument of signIn(). The examples provided are: signIn("identity-server4", null, { prompt: "login" }) // always ask ...

What are the steps to modify the sign in page on keystone.js?

I recently started using keystone.js and I'm having trouble locating the sign in page within the files. I've searched through all of the keystone.js files but can't seem to find where it's written. Can someone please guide me on how to ...

Learn how to convert data to lowercase using Vue.js 2

I am attempting to convert some data to lowercase (always lowercase) I am creating a search input like : <template id="search"> <div> <input type="text" v-model="search"> <li v-show="'hello'.includes(sea ...

"Exploring the world of JavaScript, Ajax, PHP parser errors, and the process of obtaining post data

Having an issue with the AJAX functionality in my game.php file. Despite my efforts to refresh .refre, I keep encountering a "parsererror" message. The jsonString variable is created using JSON.stringify(object). <div class="refre"></div> < ...

Protractor troubleshooting: Issues preventing execution of protractor tests

My tests suddenly started throwing an error. Everything was working fine before this. Any advice on how to fix it? Here is my Config file: exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', allScriptsTimeout: 20000, baseU ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

What is the most efficient way to create a bufferGeometry with multiple particle sizes for optimal performance?

Using a bufferGeometry, I created a THREE.Point object to display thousands of particles with the PointsMaterial material. Changing textures and colors on runtime worked perfectly for me. However, I faced an issue when trying to have particles of differen ...

How can you generate a Base64 string with Node.js?

I recently utilized the html2pdf npm package to generate a base64 string of a PDF file and then sent it to my Node.js server. I used Nodemailer to send this PDF as an email attachment by configuring the mailOptions object like so: let mailOptions ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

Is it possible to assign a value directly to a pointer variable?

I am struggling to comprehend the assignment of string2 in this code snippet: #include <stdio.h> void copy1( char * const s1, const char * const s2 ); /* prototype */ void copy2( char *s1, const char *s2 ); /* prototype */ int main( void ) { c ...

Ways to Update the Name of a Class Depending on the Elements in an Array

I am new to JavaScript, so please explain in simple terms. In the code snippet below, I need to change the class name of specific array elements - namely orange, yellow, and violet to use the class btn btn-outline-dark. Can this be achieved without adding ...

What is the best way to have a sound play when the page is loaded?

Is there a way to automatically play a sound when the page loads? <audio src="song.mp3"> Your browser does not support the audio element. </audio> I've attempted it with the following method: <script type="text/javasc ...

Learn the process of uploading an image to Firebase storage from the server side

I'm working on implementing an upload feature that utilizes Firebase storage on the server side. Here is the upload function on the server side: const functions = require("firebase-functions"); const admin = require("firebase-admin&quo ...

Transferring and bringing in components in React without ES6

I'm currently working on a react project and I want to export my ShoppingList class. However, I prefer not to use ES6 as I find it confusing. Here is the code for the ShoppingList class: class ShoppingList extends React.Component { render() { ...

How can I show a div beneath a row in an HTML table?

Check out the code snippet below: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <style type="text/cs ...

Tips on showcasing Java map information obtained from the backend on an Angular/Typescript interface

I have a 'detailsMap : any' variable from the backend that contains multiple rows in the format (key1,key2). I need to display this data in the UI using TypeScript/Angular2. Please advise on how I can achieve this. key1 : { Name:'ABC' , ...

Implement a jQuery Animation into a Vanilla JavaScript Script

I'm still getting the hang of jQuery (and JavaScript in general) and I've been working on adding a fade-in effect to my JS function that switches images in a photo gallery when a "thumbnail" is clicked. Here's my code: // HTML for the "thumb ...