Adjust the month to be plotted on the X-axis of the ColumnChart using the specified

My ORIGINAL POST:

I've put together a fiddle to showcase how my data is sourced from JSON and displayed in a ColumnChart.

https://jsfiddle.net/w4dokdt9/3/

This is an example of how my JSON data is structured:

[{"lPlusScoreID":1,"jan":60.03,"feb":43.57,"mar":48.55},
 {"lPlusScoreID":2, "jan":89.42,"feb":85.71,"mar":90.46},
 {"lPlusScoreID":3,"jan":86.22,"feb":90.61,"mar":89.53}]

The resulting column chart looks like this: Link to Chart Image

My objective is to have months along the x-axis and products as columns/bars.

How can I achieve this? I'd prefer using a Google Visualization chart, method, or configuration option. If data transformation through coding is necessary, I'm open to it, but I'm new to development.

Thank you for any assistance!

Here's my EDITED POST:

I've managed to implement the code below.

  1. Created dataArray_input with predefined months and then populated it with data from the original JSON.
  2. Utilized the transposeArray() function to transpose dataArray_input into dataArray_trans.

    function transposeArray(a) {
    return Object.keys(a[0]).map(function (c) {
        return a.map(function (r) {
            return r[c];
        });
    });  }
    
  3. Appended dataArray_trans to the final dataArray_output using the appendArray() function, which is then used by the Google API.

    function appendArray(a, b) {
    for (var i = 0; i < a.length; i++) {
        b.push(a[i]);
    }    }
    

Below is the final code snippet.

I'd appreciate feedback to ensure I'm progressing in the right direction. I'm new to this field.

Special thanks to @WhiteHat for the prompt and effective solution.

Code snippet:


Answer №1

when utilizing google charts, the key lies in how the data is provided to generate the chart

there exist various methods for manipulating data such as group() and join()
but there aren't specific methods for pivoting from columns to rows, for example...

for the specific chart that is needed, the data must be formatted as shown below...

['month', 'Product1', 'Product2']
['jan', 60.03, 89.42]
['feb', 43.57, 85.71]

refer to the live snippet below for a working example...

the data table is initialized with a single column for the month
additional columns are appended for each "lPlusScoreID"

the getFilteredRows data table method is utilized to check if the month has already been included as a row
if it has, the row is updated; otherwise, a new row is added

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var jsonData = [
    {"lPlusScoreID":1, "jan":60.03, "feb":43.57, "mar":48.55},
    {"lPlusScoreID":2, "jan":89.42, "feb":85.71, "mar":90.46},
    {"lPlusScoreID":3, "jan":86.22, "feb":90.61, "mar":89.53}
  ];

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');

  // generate data
  jsonData.forEach(function (row) {
    var colIndex;
    var rowIndex;

    // handle each key in the row object
    Object.keys(row).forEach(function (key) {
      // create column for ID
      if (key === 'lPlusScoreID') {
        colIndex = data.addColumn('number', 'Product' + row.lPlusScoreID.toString());
        return;
      }

      // locate / insert row for month
      rowIndex = getRowIndex(key);
      if (rowIndex === null) {
        rowIndex = data.addRow();
        data.setValue(rowIndex, 0, key);
      }
      data.setValue(rowIndex, colIndex, row[key]);
    });
  });

  function getRowIndex(rowMonth) {
    var rowIndex = data.getFilteredRows([{
      column: 0,
      value: rowMonth
    }]);
    if (rowIndex.length > 0) {
      return rowIndex[0];
    }
    return null;
  }

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></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

Make sure to wait for the loop to complete before moving on to the next line

I am currently leveraging the capabilities of the GitHub API to fetch a list of repositories. Subsequently, I iterate over each repository and initiate another HTTP request to obtain the most recent commit date. How can I orchestrate the iteration process ...

Issue with Bootstrap side navbar not collapsing when clicked on a link

Currently, I'm working on creating a website for a friend. While I used to have some experience with coding in the past, it has been a while and I am a bit rusty. This time around, I decided to use bootstrap for the project. However, I'm struggli ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

Failure to establish connection between electron/socket.io client and python-socketio/aiohttp server

My websocket connection is failing at the moment, even though it was working perfectly just a couple of days ago. I attempted to fix the issue by downgrading electron from version 6 to 5.0.6, but unfortunately, this did not resolve the problem. https://i. ...

Dialogue and Data Retrieval: A Powerful Combination

Once I invoke retrieve and rank within a conversation context, I extract the JSON data from the conversation and set a variable: ("call_retrieve_and_rank": true) on my server (python). When this variable is true, it triggers a search using retrieve and R ...

Issue: TypeError - 'process.env' can only accept a configurable while installing windows-build-tools

Unable to successfully download installers. Encountered an error: TypeError: 'process.env' can only accept a configurable, writable, and enumerable data descriptor. I attempted to resolve this issue by running the command npm install --global wi ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

JavaScript has the ability to sort tables using tags

I am currently working on a Vue project where I am attempting to filter my table based on the tags that users click. I have created a method that outputs all the rows containing the tag clicked by the user. <el-table-column prop="Keyword" labe ...

The performance implications of implicit returns in Coffeescript and their effects on side effects

Currently, I am developing a node.js web service using Express.js and Mongoose. Recently, I decided to experiment with CoffeeScript to see if it offers any advantages. However, I have come across something that has left me a bit unsettled and I would appre ...

A guide to decoding a variety of data types from a stream

I am currently facing a challenge in unmarshalling a JSON encoded stream of objects with different, known types into Go structs. For the purpose of illustration, here is a sample slice: [ { "uid": "xyz1", "type ...

The $mdSticky feature in AngularJS Material seems to be malfunctioning

It's been a challenge for me to get the md-toolbar to stay in the top position. I decided to create a custom directive using the $mdSticky service in AngularJS. var app=angular.module('app',['ngMaterial']); app.controller(&apos ...

Converting a Form to JSON Format Using JQuerySerialize

After using the code below to generate an array, I am now seeking to create a more intricate JSON object structured like the following: <script> $('document').ready(function() { var $myform = $("#myform"), $userDat ...

Unable to delete a row from a dynamically generated table using jQuery

I am currently working on a project that involves creating a table based on results from a servlet. The table includes checkboxes, and when a checkbox is checked, a button at the bottom of the table should appear. This button calls a remove function to del ...

Is there a way to access an object stored on my server using JavaScript?

In implementing JavaScript, I wish to define two objects stored in a file named file.txt, and utilize them within my code. For instance, I have included the following snippet in my index.php: var counter = Number(localStorage.getItem('rans')) ...

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...

Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice? function updateBackgroundColor(platz_id) { if(document.getElementById(platz_id).style.backgroundCol ...

Ways to verify the presence of a key within an array of objects

I'm on a mission to determine whether a specified key exists in an array of objects. If the key value is present, I need to return true; otherwise, false. I enter the key into a text box as input and then attempt to check if it exists in the array of ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...