Use JSON data to populate a dynamic bar chart in Highcharts

As a beginner in parsing JSON objects to highcharts, I am trying to create a basic bar graph. I have managed to set up the title of the graph, but I am having trouble displaying the series that I want to show (count as series and qpAnswer as xAxis).

Below is the JSON data that I am working with:

[
  {
    qpQuestion: "Is that a dog?",
    qpAnswerId: "1",
    qpAnswer: "Yes",
    count: "0"
  },
  {
    qpQuestion: "Is that a dog?",
    qpAnswerId: "2",
    qpAnswer: "No",
    count: "0"
  },
  {
      qpQuestion: "Is that a dog?",
      qpAnswerId: "3",
      qpAnswer: "ok",
      count: "0"
  }
]

Here is my JS code:

var url = "sections.php?request=graph";
$.getJSON(url, function(data1){

    var options = {
        chart: {
            renderTo: 'container',
            type: 'column'
        },
        title: {
            text: data1[0].qpQuestion
        },
        xAxis:{
            categories: data1.qpAnswer,
            title: {
                text: 'Answer'
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Answer Count'
            }
        }, 
        series: data1
    };

    var chart = new Highcharts.Chart(options);
});

Answer №1

To transform the data beforehand, follow these steps:

var answers = ['Yes','No' ,'OK'];
var answer_counts= [
            {name: 'Yes', data : [2,0,0]},
            {name: 'No', data: [0,3,0]},
            {name: 'OK', data: [0,0,1]} ];

Next, utilize this code to plot the data:

var options={
                chart: {
                    renderTo: 'container',
                    type: 'column'
                },
                title: {
                    text:'QA Answers'
                },
                xAxis:{
                    categories: answers,
                    title: {
                        text: 'Answer'
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: 'Answer Count'
                    }
                }, 
                series:answer_counts
           };

var chart = new Highcharts.Chart(options);

If you want to view a working example, check out this fiddle: http://jsfiddle.net/gwC2V/1/

Feel free to reach out if you need more assistance.

Answer №2

Here is an example to assist you

The JSON data is provided below

[
    [1,12],
    [2,5],
    [3,18],
    [4,13],
    [5,7],
    [6,4],
    [7,9],
    [8,10],
    [9,15],
    [10,22]
]

Use the getJSON() method to retrieve information from the JSON file and display it in a CHART

$(document).ready(function() {

    var options = {
        chart: {
            renderTo: 'container',
            type: 'spline'
        },
        series: [{}]
    };

    $.getJSON('data.json', function(data) {
        options.series[0].data = data;
        var chart = new Highcharts.Chart(options);
    });

});

For further details, check out this link

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

Query Using AngularJS for Multiple Selection

I am facing an issue with my Angular Search app. When I try to add multiple selection boxes, they do not work cumulatively. For example, if I select "Cervical" in the first box and then "Muscle" in the second box, it unselects "Cervical". What should I be ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

Tips for toggling Bootstrap 5 tabs using JavaScript instead of the button version

I am looking to switch tabs programmatically using bootstrap 5. The Bootstrap documentation recommends using buttons for tabs instead of links for a dynamic change. Here is the code I have: $("#mybut").click(function() { var sel = document.querySelector( ...

Guide on transferring binary image data to a JavaScript function

I have $comment->image_data as the binary data of the image and I want to pass this data to the imgclick() function. Attempting the method below, but encountering an unexpected token error. <img src="data:image/jpg;base64,'.$comment->image_t ...

Retrieve data from a large log file, one line at a time, and save it into a variable using nodejs

I have a massive line-delimited JSON file with over 10 million lines. How can I stream it and save specific attributes to another variable for further processing and filtering? Below is the code I tried: const readline = require('readline'); con ...

Getting started with React Native project

Just dipping my toes into the world of React Native and looking for recommendations on the best starter kit/generator to kickstart my projects. Tried out "create-react-native-app" already, but curious if there are any other generators or kits out there tha ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Response from a Discord.NET bot for web searches

So I've developed this amazing Discord Bot that provides basic responses. For instance: User Input: !Query status Bot Output: Online! These responses are pretty straightforward, but now I want to take it up a notch and enable the bot to search the w ...

The comparison between local variables and data can result in a significant drop in performance

My current project involves VueJS and Cesium, but I'm facing a performance issue with a significant drop in frame rate. While I have identified the problem area, I am unsure of why this is happening and how to resolve it. export default { name: ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...

Middleware for automatically populating a Jade variable in all app.get() routes

I have a unique setup with my Jade file system where all templates extend layout.jade. In this main template, I need to include a logout button only when the user is logged in (this information is stored in req.session). So within layout.jade, there will ...

Create a new variable and compile the sass/less file when it is requested

I'm exploring options to utilize Node.js or another server-side language to handle a specific type of request. For instance, receiving a request like this: The goal is to extract the value from the URL parameter and use it to dynamically update a var ...

What is the best way to transfer a row value from one table to another and then reinsert it back into the original table

I attempted to transfer a row value from one table to another and then back to the original table, but unfortunately, I was unable to find a solution. $('#one tbody tr td input.checkbox').click(function() { if ($(this).attr('checked&apo ...

Get the username from Parse instead of using the ObjectID

When using angular and Parse for JavaScript, I have implemented a search field where an admin can input the objectid of a user to display their details. However, I would like to modify this functionality so that the admin can enter the username instead of ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

The choice between using "npm install" and "npm install -g" for

New to the world of node, and feeling a bit lost when it comes to all this "install" stuff. Could someone clarify for me, what sets apart install from install -g? If something is installed with install -g, can it be accessed from anywhere, or is it restr ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

What advantages does NextJS offer that set it apart from other frameworks that also provide Server Side Render solutions?

I'm diving into the world of NextJS and as I explore this topic, one burning question arises: "What is the necessity of utilizing NextJS?" From what I understand, NextJS excels in rendering pages from the server and is heavily reliant on ReactJS. Howe ...

Newly inserted JSON component remains invisible

I am currently using express.js to create an API. My mongoose is returning a JSON object and I need to append an element to each item in the result.docs. This is how I am attempting to achieve that: for(let a in result.docs) { result.docs[a].link ...