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

Tips for generating automatic views in Backbone without manual instantiation

Is there a more efficient way to instantiate the view rather than directly below the definition? var BVApp = Backbone.View.extend({ Name: 'BVApp', // do chonka stuff }); $A.Class.add(new BVApp()); ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

While trying to install express using Node.js, an error (error:0906D06C :PEM routines : PEM_read_bio npm) occurred

I recently installed node.js on my computer and npm came along with it. However, when I try to execute "npm install express" in my Windows command prompt, I encounter the following error message. Can anyone guide me on how to resolve this issue? C:\U ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...

CSS grid challenges on a massive scale

My CSS grid timeline is currently generating around 1300 divs, causing performance issues. Is there a way to style or interact with the empty nodes without rendering all of them? I also want each cell to be clickable and change color on hover. Any suggest ...

Showing outcomes from various API requests

I have encountered an issue while making two API calls to a backend server and trying to display both responses in JSON format to the user. Strangely, alert 2 is showing as 'undefined' when I check the console, while alert 1 works perfectly fine. ...

Changing a JSON file using Qt

I am looking to manipulate an existing JSON file by making changes such as replacing, deleting, and adding objects, arrays, and key-value pairs before saving the modifications back to the file. Currently, I have been attempting to edit a JSON file that l ...

Unlocking two features with just a single tap

I am currently working on a website for a kiosk, where the site transitions like a photoslide between each section. To achieve this effect, I have added a layover/mask on the initial page. The layover/mask is removed using a mouse click function. This is ...

Discontinuing the fieldset tab interface feature from a Dexterity content type

I am looking to modify a condition to prevent the loading of certain javascript code when inserting an object of my content type. The current condition works only when editing the object: <?xml version="1.0"?> <object name="portal_javascripts"> ...

Mirror the content of my div code onto a two-dimensional plane using an A-frame

Query I am currently developing a 3D scene using A-Frame () and I am in need of a solution to mirror an HTML div onto a plane within the A-Frame environment. For instance, imagine a scenario where there is a div at the bottom left corner of the screen fun ...

I'm experimenting with using jQuery toggle to switch between text and images on my webpage

I attempted to use jquery "toggle" in order to hide the div containing text and display an image instead, and vice versa. However, when I click on the button, it does not work as expected. The button is from a bootstrap example - could that be the source o ...

Using Node.js and Multer to update a file uploaded to MongoDB

I have a website that allows users to upload files, but I also want them to be able to edit those files. This would involve the user pressing "edit" and replacing the existing file in the database with a new one. Normally, you can use findByIdAndUpdate for ...

Is it possible to utilize ko.observableArray in the form of a map?

Can an ko.observableArray be used as a map or dictionary? For instance: var arr = ko.observableArray(); arr.push('key', { '.. Some object as value ..' }); And then retrieve the value using the key: var value = arr['key']; ...

Tips on accessing and modifying JSON key values

I am currently using python2.7 Each time I request a JSON, it is constantly changing. My goal is to extract the value of Animal_Target_DisplayName under Term7 within Relation6 in my dictionary. The issue arises when Relation6 is nested differently or lo ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Vue.js HTML5 Editor_vueful

I am currently utilizing browserify and attempting to incorporate the vue-html5-editor library from https://github.com/PeakTai/vue-html5-editor. However, when I attempt the following code: Vue.use(require('vue-html5-editor')); An error is thro ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

JavaScript Pagination and JSON Concerns in Coding Techniques

Currently, I am pre-caching a dataset with a maximum limit of 500. The Ajax request fetches all the data at once, allowing for front loading and pagination. Everything works fine this way. However, we are in the process of transitioning our backend archit ...

Ajax UpdateProgress not functional

How can I resolve the issue where my AJAX UpdateProgress bar in ASP.NET is not running when executing a query in the correct format upon button click? Any solutions or help would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtml"> ...

How to Remove Carousel Arrows in Bootstrap 5

Any suggestions on how to remove the previous and next arrows in a Bootstrap carousel, particularly on the first and last slide? I'm struggling to find a solution for Bootstrap 5 as most solutions available are for older versions. Your help would be g ...