Generating charts using JSON data with the help of JavaScript

Hi there! I have a JSON file shown in the first image and I would like to create a chart similar to the one in the second image using JavaScript (using any library). Can anyone provide me with a simple example code on how to achieve this?

Answer №1

ZingChart could be a great solution for this particular scenario. Check out the example below:

var myConfig = {
 type: "bar", 
 "scale-x":{
  "values":[
    "ahbass marrakech",
    "massira 1 marrakech",
    "rue laayoune marrakech"
    ]
},
series : [
{
values : [2,1,1]
}
]
};

zingchart.render({ 
id : 'myChart', 
data : myConfig, 
height: 400, 
width: 600 
});
<!DOCTYPE html>
<html>
<head>
<!--Assets will be injected here on compile. Use the assets button above-->
<script src= "https://cdn.zingchart.com/zingchart.min.js"></script>
<script> zingchart.MODULESDIR = "https://cdn.zingchart.com/modules/";
ZC.LICENSE = ["569d52cefae586f634c54f86dc99e6a9","ee6b7db5b51705a13dc2339db3edaf6d"];</script>
<!--Inject End-->
</head>
<body>
<div id='myChart'></div>
</body>
</html>

If you are exploring your options, you might find this comparison of JavaScript charting frameworks useful.

Just to be transparent, I am part of the ZingChart team. Feel free to reach out if you have any questions about the demonstration.

Answer №2

Check out CanvasJS.

Here is an illustrative example of how to display a chart using data from an external JSON file.

$(document).ready(function() {
  var datapoints = [];
  $.getJSON("https://api.myjson.com/bins/45rin", function(result) {
    for (var i = 0; i <= result.datapoints.length - 1; i++) {
      datapoints.push({
        label: result.datapoints[i].label,
        y: parseInt(result.datapoints[i].y)
      });
    }

    var chart = new CanvasJS.Chart("chartContainer", {
      data: [{
        type: "column",
        datapoints: datapoints
      }]
    });

    chart.render();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

Answer №3

Google Charts is an excellent tool for creating charts and graphs using JavaScript, especially for beginners. I remember using it when I was exploring different charting libraries in JS.

<html>
    <head>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">
            google.charts.load('current', {'packages':['corechart']});
            google.charts.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Age', 'Weight'],
                    [8,   12],
                    [4,   5.5],
                    [11,  14],
                    [4,   5],
                    [3,   3.5],
                    [6.5, 7],
                ]);

                var options = {
                    title: 'Age vs. Weight comparison',
                    hAxis: {title: 'Age', minValue: 0, maxValue: 15},
                    vAxis: {title: 'Weight', minValue: 0, maxValue: 15},
                    legend: 'none'
                };

                var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <div id="chart" style="width:900px;height:500px;"></div>
    </body>
</html>

When you run the code above, you will see the chart like this: https://i.stack.imgur.com/UikVP.png

If you have JSON data, consider using JSON.parse to dynamically load the data instead of hard-coding it as shown in my example.

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

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Here is a guide on how to develop a PHP function that interacts with a textarea to display text in the specified color by using syntax like [color:red]

Is it possible to code a PHP function that can work alongside a textarea to display text in the specified color by using a syntax like [color:red]? This function operates in a similar manner to Facebook's @[profile_id:0] feature. ...

Transforming a collection of Plain Old Java Objects into JSON will solely display the "id" attributes

I encountered an unusual issue with my project setup. I created a REST endpoint by bootstrapping a mvn archetype using Jersey, Grizzly2, and Moxy. This endpoint is supposed to return a Set of all POJOs in the DataSource. However, when I make a @GET request ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

Encountering a problem while attempting to incorporate SQLite into a Node.js environment

I've encountered issues while attempting to import SQLite into node. Here is my import statement: import * as sqlite from './sqlite'; But unfortunately, I am receiving the following error message: node:internal/process/esm_loader:74 int ...

Is there a way to select and handle multiple elements using async wdio with the same selector?

My test scenario involves using async wdio to test my React app, where I need to count elements with a specific selector and check their contents. The code snippet being tested is as follows: <div className='container'> <li className= ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

From Panda's Den to JSON Empire: Unraveling the Dataframe

After an exhaustive review and attempt at implementing all the other solutions on SO related to this challenge, I have yet to find a working solution. Question: How can I convert employee and supervisor pairs into a dynamic hierarchical JSON structure for ...

python decoding json using Twisted

Here's the code I've written using the Python Twisted library: class Cache(protocol.Protocol): def __init__(self, factory): self.factory = factory def dataReceived(self, data): request = json.loads(data) self.fac ...

Update: Cannot mark as invalid a nested document that has not been included in an array

I recently encountered an issue with my upsert query in mongoose. It was functioning perfectly in version 3.8, but ever since I upgraded to version 4, I've been facing the following error: Unable to invalidate a subdocument that has not been added to ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

Update the content of the page without reloading images

Is there a way to refresh a webpage on click without refreshing the images, only the text content? Can this be achieved without clearing the cache? I attempted to refresh the entire page with the following JavaScript code: <script> $(".secon ...

How to assign the 'src' attribute to an HTML element using Node.js

I am currently using 'express' in Node.js and have implemented the following code to send a URL input into text: <form method="GET" action='/download' class="my-5"> <div class="form-group"> ...

Javascript Developer Platform glitches

Describing this issue is proving difficult, and I have been unable to find any solutions online. My knowledge of Javascript and its technologies is still quite new. I am currently working on a web application using NodeJS, Express, and Jade that was assig ...

Updating Arrays in Node.js isn't happening as expected

Hello, I have a function that I am calling from my controller like this: var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id); but the controller is returning an empty array as a result. However, when I log the result in my model, ...

Retrieve the values and IDs for every span element within the form

I have been attempting to retrieve all span elements within a form and make them editable input text fields. Once you click away, they should revert back to span elements. I will provide a live example in the attached fiddle. I tried my hand at it, but the ...