Read google sheet json data into chartjs

99封情书 提交于 2021-01-28 05:43:36

问题


I have a google sheet with simple two colomns, one labels and the other is values. I succeeded to convert it into json, and using such values in tables using the following js

$.getJSON("https://spreadsheets.google.com/feeds/list/1GnakUnNQvFXjuzMSPnBpU9eufb4SooQLGL2oFc3lfAs/od6/public/values?alt=json", function (data) {

      var sheetData = data.feed.entry;

      var i;
      for (i = 0; i < sheetData.length; i++) {

        var names = data.feed.entry[i]['gsx$names']['$t'];
        var numbers = data.feed.entry[i]['gsx$numbers']['$t'];



      }
    });

And want to use it in a radar chart.js, which I managed to make it work, but only with hardcoded data

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};
var chartColors = {
    red: 'rgba(253, 48, 76)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgba(240,236,211)',
    green: 'rgb(75, 192, 192)',
    blue: 'rgba(42,105,163)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgba(48,48,50)'
};

var color = Chart.helpers.color;
var config = {
  type: 'radar',
  data: {
    labels: [
      "label1",
      "label2", "label3", "label3", "label4", "label5", "label6"
    ],
    datasets: [{
      label: "Current level",
      backgroundColor: color(chartColors.red).alpha(0.2).rgbString(),
      borderColor: chartColors.red,
      pointBackgroundColor: chartColors.red,
      data: [
        95,
        65,
        74,
        87,
        70,
        78,
        93
      ]
    }, {
      label: "Goal level",
      backgroundColor: color(chartColors.blue).alpha(0.2).rgbString(),
      borderColor: chartColors.blue,
      pointBackgroundColor: chartColors.blue,
      data: [
        95,
        80,
        85,
        90,
        89,
        87,
        95
      ]
    }, ]
  },
  options: {
    legend: {
      position: 'top',
      labels: {
        fontColor: 'white'
      }
    },
    title: {
      display: true,
      text: 'Curent level vs goal',
      fontColor: 'white'
    },
      maintainAspectRatio: false,
    scale: {
      ticks: {
        beginAtZero: true,
        fontColor: 'white', // labels such as 10, 20, etc
        showLabelBackdrop: false // hide square behind text
      },
      pointLabels: {
        fontColor: 'white' // labels around the edge like 'Running'
      },
      gridLines: {
        color: 'rgba(255, 255, 255, 0.2)'
      },
      angleLines: {
        color: 'white' // lines radiating from the center
      }
    }
  }
};

// A plugin to draw the background color
Chart.plugins.register({
  beforeDraw: function(chartInstance) {
    var ctx = chartInstance.chart.ctx;
    ctx.fillStyle = '#303032';
    ctx.fillRect(0, 0, chartInstance.chart.width, chartInstance.chart.height);
  }
})

window.myRadar = new Chart(document.getElementById("canvas"), config);

The problem is I can't get them both to work together, in a sense, if I add a new row (label and value), it will update chart, I tried to substitute the data part in the chart code with the variables I created (names and numbers), but it didn't work. Also, I'm planning to use it with d3 as well not just chart.js, as well as adding new columns, does it work the same way?


回答1:


Please remind that jQuery.getJSON() is executed asynchronously. Therefore you should create the chart only once the data is available and processed to a format suitable for your chart. This can be done if you place code responsible for chart creation inside the jQuery.getJSON() success handler (callback function) as follows.

$.getJSON("https://spreadsheets.google.com/feeds/list/1GnakUnNQvFXjuzMSPnBpU9eufb4SooQLGL2oFc3lfAs/od6/public/values?alt=json", data => {
  var labels = [];
  var numbers = [];
  data.feed.entry.forEach(e => {
    labels.push(e['gsx$names']['$t']);
    numbers.push(Number(e['gsx$numbers']['$t']));
  });
  new Chart(document.getElementById('myChart'), {
    type: 'radar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Current level',
        data: numbers,
        backgroundColor: 'rgba(253, 48, 76, 0.2)',
        borderColor: 'rgb(253, 48, 76)',
        pointBackgroundColor: 'rgb(253, 48, 76)'
      }]
    },
    options: {
      tooltips: {
        callbacks: {
          title: (tooltipItem, data) => data.labels[tooltipItem[0].index]
        }
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>


来源:https://stackoverflow.com/questions/60183572/read-google-sheet-json-data-into-chartjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!