What issues are present in the provided code? What is preventing the graph from being displayed as intended?

My goal is to create a line graph using CanvasJS with data sourced from an external JSON file. The JSON file includes Date, high, open, low, vol, and price values. The graph should display Date, high, open, and low values only.

This is the code I have written:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script>

window.onload = function () {
    var dataPoints1 = [];
    var dataPoints2 = [];
    var dataPoints3 = [];

    var chart = new CanvasJS.Chart("chartContainer", {
title:{
    text: "Data"
},
axisX:{
    title:"Date"
},
axisY:[{
    title: "Open",
    lineColor: "#C24642",
    tickColor: "#C24642",
    labelFontColor: "#C24642",
    titleFontColor: "#C24642"

},
{
    title: "High",
    lineColor: "#369EAD",
    tickColor: "#369EAD",
    labelFontColor: "#369EAD",
    titleFontColor: "#369EAD"
}],
axisY2: {
    title: "Low",
    lineColor: "#7F6084",
    tickColor: "#7F6084",
    labelFontColor: "#7F6084",
    titleFontColor: "#7F6084"
},
toolTip: {
    shared: true
},
legend: {
    cursor: "pointer",
    itemclick: toggleDataSeries
},
data: [{
    type: "line",
    name: "High",
    color: "#369EAD",
    showInLegend: true,
    axisYIndex: 1,
    dataPoints: dataPoints1
},
{
    type: "line",
    name: "Open",
    color: "#C24642",
    axisYIndex: 0,
    showInLegend: true,
    dataPoints: dataPoints2
},
{
    type: "line",
    name: "Low",
    color: "#7F6084",
    axisYType: "secondary",
    showInLegend: true,
    dataPoints: dataPoints3
}]
});

$.getJSON("q_data.json", callback); 

function callback(data) {   
for (var i = 0; i < data.length; i++) {
    dataPoints1.push({
        x: data[i].Date,
        y: data[i].open
    });
    dataPoints2.push({
        x: data[i].Date,
        y: data[i].high
    });
    dataPoints3.push({
        x: data[i].Date,
        y: data[i].low
    });
}
chart.render(); 
    }

function toggleDataSeries(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
    e.dataSeries.visible = false;
} else {
    e.dataSeries.visible = true;
}
e.chart.render();
}
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; max-width: 920px; margin: 0px auto;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</body>
</html>

Although I expect the plotted line graph to be displayed, it only shows the y-axis, x-axis, and the title of the graph without any error messages.

Answer №1

CanvasJS only supports number and date-time values in the x-axis, but the sample JSON you provided contains x-values as strings. Converting them to date objects while parsing the JSON should resolve this issue.

var dataPoints1 = [];
var dataPoints2 = [];
var dataPoints3 = [];

var chart = new CanvasJS.Chart("chartContainer", {
  title:{
    text: "Data"
  },
  axisX:{
    title:"Date"
  },
  axisY:[{
    title: "Open",
    lineColor: "#C24642",
    tickColor: "#C24642",
    labelFontColor: "#C24642",
    titleFontColor: "#C24642"

  },{
    title: "High",
    lineColor: "#369EAD",
    tickColor: "#369EAD",
    labelFontColor: "#369EAD",
    titleFontColor: "#369EAD"
  }],
  axisY2: {
    title: "Low",
    lineColor: "#7F6084",
    tickColor: "#7F6084",
    labelFontColor: "#7F6084",
    titleFontColor: "#7F6084"
  },
  toolTip: {
    shared: true
  },
  legend: {
    cursor: "pointer",
    itemclick: toggleDataSeries
  },
  data: [{
    type: "line",
    name: "High",
    color: "#369EAD",
    showInLegend: true,
    axisYIndex: 1,
    dataPoints: dataPoints1
  },{
    type: "line",
    name: "Open",
    color: "#C24642",
    axisYIndex: 0,
    showInLegend: true,
    dataPoints: dataPoints2
   },{
    type: "line",
    name: "Low",
    color: "#7F6084",
    axisYType: "secondary",
    showInLegend: true,
    dataPoints: dataPoints3
  }]
});

$.getJSON("https://api.myjson.com/bins/1gfuo7", callback); 

function callback(data) {
  for (var i = 0; i < data.length; i++) {
    dataPoints1.push({
      x: new Date(data[i].Date),
      y: data[i].open
    });
    dataPoints2.push({
      x: new Date(data[i].Date),
      y: data[i].high
    });
    dataPoints3.push({
      x: new Date(data[i].Date),
      y: data[i].low
    });
  }
  chart.render(); 
}

function toggleDataSeries(e) {
  if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
    e.dataSeries.visible = false;
  } else {
    e.dataSeries.visible = true;
  }
  e.chart.render();
}
<div id="chartContainer" style="height: 250px; max-width: 920px; margin: 0px auto;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

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

marking locations on Google Maps with pins

Is there a simpler method to pinpoint multiple locations on a Google map? I have numerous coordinates to mark, and the current process is quite challenging. The current method involves using the following controller: .controller('MapCtrl', func ...

JavaScript Restful Framework

My upcoming project involves creating a complex web application using JavaScript. I've decided to utilize CanJS for organizing the client-side elements. I'm leaning towards using Node.js for the server-side portion, but I'm unsure of the be ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

What is the best way to pass variables between nested directives?

When a directive called el2 is nested within another directive called el1, I face challenges in accessing variables that are "locally declared" in el1 (such as variables generated by ng-repeat, ng-init, etc) from el2. For a practical example showcasing th ...

Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it en ...

Differences between a traditional post request and an asynchronous ajax request

I am working with a table that contains various items. Once I select an item and click a button, I need to send its ID to the server side in order to generate an Excel file based on that ID. Should I use the traditional method of sending the ID from the ...

Is there a way to make the fixed table header scroll along with the table body data?

I am facing an issue with my table where I have multiple columns. I have managed to fix the table header successfully, however, when I scroll horizontally through the table body columns, the header remains fixed and does not move accordingly. How can I res ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

google visualization api - displaying multiple y-axis values for a single date on x-axis

I have a dataset that I need to graph with some given values. Here is how my data is structured... (Date on the x-axis and Values on the y-axis) || Date || X1 || X2 || X3 || || 01-01-2008 || 1 || 2 || 3 || || 01-01-2008 || 2 || 3 || 4 || ...

Guide to making a slider menu using html, css, and javascript

Just dipping my toes into the world of web development. I'm intrigued by the idea of creating a "slider menu" where users can view and select options by clicking on next or previous buttons (see example image below). While I've got some basic HTM ...

Is there a way to configure Omniauth to utilize JSON for callback responses?

Currently, I am working on implementing Omniauth into a Rails API for use with an Android application. My goal is to manage the omniauth callback using JSON. Typically, Omniauth directs its callbacks to /auth/:provider/callback. Is there a method availabl ...

Exploring Node.js: Uncovering the Node Path in Windows Operating System

https://i.sstatic.net/zeI3T.jpg Hello there, Attached below is the picture showing the configuration settings for the Ponicode extension, which is used for automating unit tests. I'm currently trying to locate the Node Path for Node.js on my Window ...

What is preventing me from assigning all padding values at once?

I attempted to modify all paddings of the html element using JavaScript, with the following code: const pd = 1 document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px' document.getElementsByClassName('board') ...

Submitting a form through AJAX on Internet Explorer 11

I am attempting to make an Ajax post using JQuery in IE11. I have updated the compatibility meta-tag for ie-9 but the post is still not being sent. Instead, it is throwing an error that says {exception} Unable to get property 'settings' of und ...

Transferring Visitor's Country Code Between Two Web Applications Using .NET Framework (ASP/MVC)

I'm currently working on developing an application that collects user information such as country, city, and IP address of the website they're visiting. This data is then sent to another web application of mine, which will be automatically update ...

Jquery method to extract and modify text within an HTML opening tag

As an example, let's consider <img onclick="remClicked(this)" src="~/images/chrest.png" /> I am interested in replacing onclick="remClicked(this)" src="~/images/chrest.png" with another text using either javascript or jquery. Is this possible? ...

Unable to retrieve the current status of Li from the backend code

I have created a code snippet to load controls on different tabs by using li elements with the attribute runat=server. However, I am facing an issue where I need to load controls based on the active li tab. How can I determine which tab was clicked from t ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

Connect various inputs in Vue.js so they can be updated simultaneously

I need to have multiple text inputs that are interconnected, so when I change the value of one input, the others should update with the same value. These inputs are being generated dynamically in a loop using v-for as shown below: <tbody> <varia ...