Learn how to create a logarithmic scale graph using CanvasJS by fetching data from an AJAX call

window.onload = function() {
  var dataPoints = [];
  // fetching the json data from api via AJAX call.
  var X = [];
  var Y = [];
  var data = [];

  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', ' https://api.myjson.com/bins/cixax', true);
    xobj.onreadystatechange = function() {
      if (xobj.readyState == 4 && xobj.status == "200") {
        callback(xobj.responseText);
      }
    }
    xobj.send(null);
  }
  loadJSON(function(response) {
    var response;
    var field = JSON.parse(response);
    var values = [];
    //Iterating and storing leads & visits in a variable.
    var $this = field;
    for (var key in $this) {
      if ($this.hasOwnProperty(key)) {
        var data = $this[key].dates;
        for (var val in data) {
          values.push({
            "X": data[val].visits,
            "Y": data[val].leads
          });
        }
      }
    }
    dataPoints = ({
      "values": values
    });
  });

  var chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Log Scale on Axis Y - Workaround using Linear Axis"
    },
    axisY: {
      //valueFormatString: "0.## E0",
      title: "In log scale",
      labelFormatter: function(e) {
        var lable = Math.pow(10, e.value);
        if (lable >= 1000)
          lable = CanvasJS.formatNumber(lable / 1000) + "k";
        else
          lable = CanvasJS.formatNumber(lable);
        return lable;
      },
      interval: 1,
      includeZero: false
    },
    toolTip: {
      contentFormatter: function(e) {
        var content = "Data Values";
        for (var i = 0; i < e.entries.length; i++) {
          content += "</br>" + e.entries[i].dataPoint.x + " : ";
          content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
        }
        return content;
      }
    },
    data: [{
      type: "line",
      dataPoints: []
    }]
  }); convertToLog(chart.options.data); chart.render();

  function convertToLog(data) {
    var dataPoints;
    for (var j = 0; j < data.length; j++) {
      dataPoints = data[j].dataPoints;
      for (var i = 0; i < dataPoints.length; i++) {
        dataPoints[i].y = Math.log10(dataPoints[i].y);
      }
    }
  }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

Attempting to plot a graph using canvasjs, input retrieved from external API with AJAX call, X and Y variables stored in array provided as input to canvasjs library for graph plotting. However, facing difficulties in drawing the graph despite the completed snippet above.

Answer №1

The Chart was not displaying properly because the render method was being called before the data had finished loading.

It's important to note that "x" and "y" should be in lowercase, not uppercase. The chart may appear jumbled because the X values in the JSON are not sorted correctly.

With the latest update, the library now supports Logarithmic Scale on the Y-Axis, providing a more efficient solution. For more information, check out this documentation link.

window.onload = function() {
  //var dataPoints = [];
  // fetching the json data from api via AJAX call.
  var X = [];
  var Y = [];
  var data = [];

  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://api.myjson.com/bins/cixax', true);
    xobj.onreadystatechange = function() {
      if (xobj.readyState == 4 && xobj.status == "200") {
        callback(xobj.responseText);
      }
    }
    xobj.send(null);
  }
  loadJSON(function(response) {
    var response;
    var field = JSON.parse(response);
    var values = [];
    //Iterating and storing leads & visits in a variable.
    var $this = field;
    for (var key in $this) {
      if ($this.hasOwnProperty(key)) {
        var data = $this[key].dates;
        for (var val in data) {
          values.push({
            "x": data[val].visits, // Should be "x" & "y"
            "y": data[val].leads 
          });
        }
      }
    }
    //dataPoints = ({
    //  "values": values
    //});
    
    // Update the dataPoints & render the chart
    // x values need to be in sorted order
    chart.options.data[0].dataPoints = values;
    
    chart.render();
  });

  var chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Log Scale on Axis Y - Workaround using Linear Axis"
    },
    axisY: {
      //valueFormatString: "0.## E0",
      title: "In log scale",
      labelFormatter: function(e) {
        var lable = Math.pow(10, e.value);
        if (lable >= 1000)
          lable = CanvasJS.formatNumber(lable / 1000) + "k";
        else
          lable = CanvasJS.formatNumber(lable);
        return lable;
      },
      interval: 1,
      includeZero: false
    },
    toolTip: {
      contentFormatter: function(e) {
        var content = "Data Values";
        for (var i = 0; i < e.entries.length; i++) {
          content += "</br>" + e.entries[i].dataPoint.x + " : ";
          content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
        }
        return content;
      }
    },
    data: [{
      type: "line",
      dataPoints: []
    }]
  }); //convertToLog(chart.options.data); chart.render();

  function convertToLog(data) { 
    var dataPoints;
    for (var j = 0; j < data.length; j++) {
      dataPoints = data[j].dataPoints;
      for (var i = 0; i < dataPoints.length; i++) {
        dataPoints[i].y = Math.log10(dataPoints[i].y);
      }
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

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

Beginner coding exercises to master JavaScript

With a proficiency in CSS, HTML, and some knowledge of Jquery and PHP, I aspire to become a Front End Web Developer. However, my lack of understanding in Javascript is holding me back. I acquired my current skillset by rapidly learning over 9 months while ...

Full comprehension with a width of 100%

Here is an example where .flex2 has 2 children. 1st child - width: 300px 2nd child - width: 100% .b{ height: 50px; } .flex2{ margin-top: 20px; display: flex; .box{ background-color: blue; width: 300px; } .box1{ backgroun ...

What steps can I take to create a responsive jQuery UI buttonset?

I am currently facing a challenge with my web app (http://www.tntech.edu/cafe-menu.php) which is being iframed into a mobile application developed by ATT. The button sizes vary on different phone models, and I am seeking a solution to make them responsiv ...

Error occurs when trying to map an array within an asynchronous function

Hey there, I have an array of objects with validation inside my async function (router.post()) and I need to map it before validating. Here is the approach I am taking: ingredients.map(({ingredient, quantity})=>{ if(ingredient.trim().length < 1 | ...

Tips for modifying link height using CSS

I'm currently facing an issue with adjusting the height of "footer a" links that are using Fontface vector icons in the footer. I have added a red border around them to visually identify the problem. Ideally, when navigating through the links, the bor ...

What steps should I take to activate JavaScript type checking in Vue files within Visual Studio Code?

After much exploration, I have successfully configured Visual Studio Code to perform type checking for JavaScript within JS files. This feature highlights any bad code and provides explanations for why it is considered as such here. However, this function ...

How can you master the art of PHP templating like a pro?

Years ago, I started a small PHP website that has since grown into quite a mess. Despite having a separate template for the final HTML output, I still find myself handling a lot of HTML within the 'business logic' part of the code. My main issue ...

Incorporate an external JavaScript script using code

I'm currently working on integrating a map widget from 'Awesome Table' into the codebase of an open-source CRM platform. The specific code snippet I need to add is <div data-type="AwesomeTableView" data-viewID="-KLtnY5OHJPgnEOX1bKf"> ...

Set the color of the text in the Material UI pagination component to a subtle shade

I would like to customize the color of the text in Material UI's pagination component. Specifically, I want the action button to be white and the text portion to be grey, similar to the left action arrow in the image below. Is there a way for me to ac ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...

Switching the background image of a div by clicking on a different div

To start, you can locate all of my code right here. http://jsfiddle.net/yfukm8kh/1/ The issue I'm encountering pertains to the following section. var changePic = function (direction, id, array) { var intID = parseInt(id); var intDir = pars ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

Issues with the Rendering of Child Components in React

I have developed a main component that contains two child elements, where one of the children is attempting to send data back to the parent's state. I am not encountering any runtime errors when running the code, but the child component that is suppos ...

What is the reason behind the reversal of the response list by $.getJSON?

Here is the code I am working with: // Setting up an array for tooltip content var Data = []; var search = $("input#field_search").val(); var combo = $("select#search_option").val(); var jsonUrl = "ajax.php?module=formation&action=get_participant_list ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

Increase a variable within a looping structure using jQuery

I am faced with a task that involves selecting two values from different dropdown lists, such as 1001 from the first dropdown and 1003 from the second. Upon clicking the 'add' button, I need to pass these selected values, along with the values in ...

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

Keep a close eye on your Vue app to make sure it's

<template> <v-form :model='agency'> <v-layout row wrap> <v-flex xs12 sm12 lg12 > <v-layout row wrap> <v-flex xs12 md12 class="add-col-padding-right"> <v-radio-group v-mod ...

What methods can I use to conceal #! from showing on the browser's address bar?

Imagine you have the below link: www.someurl.com/#!?page=index How would you convert it into one of these options: www.someurl.com/#!/index (using mod_rewrite) www.someurl.com/ajax/index (also using mod_rewrite, but replacing #! with ajax) www.someurl. ...