Creating a line chart with multiple axes using Chart.js by importing data from a Google Sheet in JSON format

My attempt to visualize the data stored in a Google Sheet using Chart.js resulted in a multi-axis line chart. The data I have looks like this:

https://i.stack.imgur.com/F8lC7.png

When trying out the following code, I encountered an issue where only the first two data points (0:00 and 1:00) were displayed instead of the entire dataset. Additionally, there was only a single Y-axis present. Can someone identify what's wrong with my code?

https://i.stack.imgur.com/gFtkq.png

function GenerateChart(labels, valuesA, valuesB, title) {
    var data = {
        labels: labels,
        datasets: [{
            label: 'Temperature',
            data: valuesA,
            },
           {
            label: title,
            data: valuesB,
            }]
    };

    var ctx = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(ctx, {
            type: 'line',
        data: {
        datasets: [{
            label: 'Temperature',
            fill: false,
            data: valuesA,
            backgroundColor: ['rgb(255, 99, 132, 0.8)']
          },{
            label: 'Relative Humidity',
            fill: false,
            data: valuesB,
            backgroundColor: ['rgb(255, 99, 132, 0.8)'],
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                xAxes: [{
                        ticks: {
                            beginAtZero: true,
                        scaleLabel: {
                        display: false,
                        labelString: ''
                    }
                    }
                }],
                yAxes: [{
                    scaleLabel: {
                        display: false,
                        labelString: ''
                    }
                }]
            },
        },
        }
]}})
    return myChart;
}


var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var json = JSON.parse(this.response);
      console.log(json);

// Map json labels back to values array
var labels = json.feed.entry.map(function (e) {
  return e.gsx$tag.$t;
});

// Map json values back to values array
var valuesA = json.feed.entry.map(function (e) {
    return e.gsx$dailytemperature.$t
});

// Map json values back to values array
var valuesB = json.feed.entry.map(function (e) {
    return e.gsx$dailyrh.$t
});

GenerateChart(labels, valuesA, valuesB, "Temperature", "Relative Humidity");
    }
  };
  xhttp.open("GET", "https://spreadsheets.google.com/", false);
  xhttp.send();

Your assistance would be greatly appreciated. Thank you for your help.

Answer №1

Oh no! The data.labels is not defined.

data: {
  labels: labels,
  ...

Additionally, the chart's options were mistakenly nested inside the second dataset. Check out the corrected code snippet below:

function BuildChart(labels, valuesa, valuesb, chartTitle) {
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'Temperature',
        fill: false,
        data: valuesa,
        backgroundColor: 'red',
        borderColor: 'red'
      }, {
        label: 'Relative Humidity',
        fill: false,
        data: valuesb,
        backgroundColor: 'blue',
        borderColor: 'blue'
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        xAxes: [{
          ticks: {
            beginAtZero: true,
            scaleLabel: {
              display: false,
              labelString: ''
            }
          }
        }],
        yAxes: [{
          scaleLabel: {
            display: false,
            labelString: ''
          }
        }]
      }
    }
  })
  return myChart;
};


var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var json = JSON.parse(this.response);

    // Mapping JSON labels back to the values array
    var labels = json.feed.entry.map(function(e) {
      return e.gsx$tag.$t;
    });

    // Mapping JSON values back to the values array
    var valuesa = json.feed.entry.map(function(e) {
      return e.gsx$dailytemperature.$t
    });

    // Mapping JSON values back to the values array
    var valuesb = json.feed.entry.map(function(e) {
      return e.gsx$dailyrh.$t
    });

    BuildChart(labels, valuesa, valuesb, "Temperature", "Relative Humidity");
  }
};
xhttp.open("GET", "https://spreadsheets.google.com/feeds/list/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/x/public/full?alt=json", false);
xhttp.send();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script> 
<canvas id="myChart""></canvas>

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

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

Transform an array of strings with specific formatting into an array of arrays

Looking to convert an array generated from a Postgres query into an array variable in Laravel? I received the following var_dump result in Laravel: 0 => array:1 [ "order_itemset" => "{8,11}" ] 1 => array:1 [ "or ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...

Issue: The function _lib_getAllUsers__WEBPACK_IMPORTED_MODULE_2___default(...) is not recognized as a valid function

I'm currently following the YouTube series on Next.js by Dave Gray. My goal is to import a function from the file "lib/getAllUsers" https://i.sstatic.net/1SQMg.png However, I'm encountering the following error: Unhandled Runtime Error Error: ...

Implementing pagination with complete page information using node.js and mongodb

Hello, I am currently working on implementing pagination in NodeJS and MongoDB. Check out the code I have written below: router.get("/PO_pagination", verify, async (req, res) => { console.log("req.query", req.query) try { let ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

How is it possible for me to retrieve data values directly from a sequelize model?

My question is straightforward - when doing a single select in sequelize, a model is returned. Inspecting this model reveals various options such as dataValues, _prevValues, _change, _options, isNewRecord, and more. What puzzles me is that you can also a ...

Leveraging directives within AngularJS

I'm currently delving into the world of AngularJS and facing a particular question that has me stumped. Let's examine the sample code snippet I put together: js var app = angular.module('customerPortalApp', ["ui.router"]); app.confi ...

Guidelines for Naming Data Attribute Values in JavaScript

When it comes to the Data Attribute Value, should one use hyphens or camelCase as a convention? Hyphen Example: <input type="text" name="some_input" data-target="to-grab-input-via-javascript"> Camel Case Example <input type="text" name="some_ ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

I am searching for a Nodejs library that has the ability to serialize and deserialize paths composed of named components, such as URL pathnames. Can

Here is an example: formatPath("/:item1/:item2/:item3", {item1: "apple", item2: "banana", item3: "cherry"}) => /apple/banana/cherry deserializePath("/:item1/:item2/:item3", "/apple/banana/cherry") => {item1: "apple", item2: "banana", item3: "cher ...

Guide on injecting javascript code containing php variables into a php page

I have successfully developed a PHP page and Javascript code that includes some PHP variables. The code is designed to insert PHP variables into the database using Javascript: <?php $id = "Kevin"; $user = "Calvin"; ?> <!-- include jquer ...

JavaScript encounters difficulty in reading the text file

I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using: <html> <head> ...

Having trouble sending data to API with Node, Express, and vanilla JavaScript POST form

I am currently utilizing Node JS along with Express JS in order to implement a form submission that pushes data into the database. Below is my form structure <form action="/pokedex/register/poke_submission" method="POST"> ...

Unable to integrate any modules or components from bit.dev into my React application

I am currently working on a React project and encountering an issue with importing a component from bit.dev. After installing the package via my terminal with the command: bit import nexxtway.react-rainbow/button You can find more information about it t ...

Transfer data from a Django template populated with items from a forloop using Ajax to a Django view

Struggling to implement a click and populate div with ajax in my django e-commerce app. The function involves clicking on a category in the men's page which then populates another div. gender.html {%for cate in cat%} <a href="javascript:getcat()" ...

jQuery Issue DetectedSlight complication spotted with jQuery

I've encountered a peculiar problem with jQuery's contains function: HTML <span class="tag diaTags label label-info">Teststring<span data-role="remove"></span></span> JS When I directly use $('span.diaTags:contai ...

Hover over the first element to remove its class and replace it with a different element

I am attempting to develop a function that adds the class = "actived" to the first Element. This class has a CSS style that highlights the element in question. I have a list of 4 lines and I want the first one to automatically receive this class, while t ...

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

Which is better: JavaScript, Json, or Html?

When working with an ASP.NET MVC view and using jQuery AJAX to update a div, the decision on whether to use a controller that returns a PartialView or JSON can depend on various factors. Consideration for both user experience and system performance is im ...