Creating an interactive Google line chart in MVC4

I am currently working on a dynamic line chart that needs to be able to adjust the number of lines (Standard, Latest, Earliest, Average) based on the database records. My code structure is similar to this example.

function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Month', 'Standard', 'Latest', 'Earliest', 'Average'],
            ['Original Documents', @Convert.ToDecimal(@Standard[0].ToString()), @Convert.ToDecimal(@Latest[0].ToString()), @Convert.ToDecimal(@Earliest[0].ToString()), @Convert.ToDecimal(@Average[0].ToString())],
            ["Filing of Entries", @Convert.ToDecimal(@Standard[1].ToString()), @Convert.ToDecimal(@Latest[1].ToString()), @Convert.ToDecimal(@Earliest[1].ToString()), @Convert.ToDecimal(@Average[1].ToString())],
            ["Assessment of Duties", @Convert.ToDecimal(@Standard[2].ToString()), @Convert.ToDecimal(@Latest[2].ToString()), @Convert.ToDecimal(@Earliest[2].ToString()), @Convert.ToDecimal(@Average[2].ToString())],
            ["Payment of Duties", @Convert.ToDecimal(@Standard[3].ToString()), @Convert.ToDecimal(@Latest[3].ToString()), @Convert.ToDecimal(@Earliest[3].toString()), Convert.ToDecimal(@Average[3].ToString())],
            ["Releasing", Convert.ToDecimal(@Standard[4].toString()), Convert.ToDecimal(@Latest[4].ToString()), Convert.ToDecimal(@Earliest[4].toString()), Convert.ToDecimal(@Average[4].toString())],
            ["Gate Pass", Convert.ToDecimal(@Standard[5].toString()), Convert.ToDecimal(@Latest[5].toString()), Convert.ToDecimal(@Earliest[5].toString()), Convert.ToDecimal(@Average[5].toString())],
            ["Delivery", Convert.ToDecimal(@Standard[6].toString()), Convert.ToDecimal(@Latest[6].toString()), Convert.ToDecimal(@Earliest[6].toString()), Convert.ToDecimal(@Average[6].toString())]
        ]);

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

Answer №1

Consider modifying your function to accept a Json array in the following format:

function drawChart(jsonData) {
    var array = JSON.parse(jsonData);
    var data = google.visualization.arrayToDataTable(array);
    var options = {
        hAxis: {
          title: 'X-Axis Legend'
        },
        vAxis: {
          title: 'Y-Axis Legend'
        }
    };
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

The data should be structured in a row-per-x-position, column-per-line format as outlined in the documentation:

Rows: Each row in the table represents a set of data points with the same x-axis location.

To populate this Json from your controller method, you can use a loop or other technique to add each new line and its corresponding data dynamically:

var data = new[] {  
    new[] {"Month", "Line1", "Line2", "Line3", "Line4"}, // Add new lines here
    new object[] {"x-label1", 1, 2, 3, 4 }, // Add data points
    new object[] {"x-label2", 11, 12, 13, 14 },
    new object[] {"x-label3", 7, 6, 2, 17 },
    new object[] {"x-label3", 17, 19, 23, 9 },
    new object[] {"x-label3", 12, 4, 11, 18 }
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

This results in the following Json being generated:

[["Month","Line1","Line2","Line3","Line4"],["x-label1",1,2,3,4],["x-label2",11,12,13,14],["x-label3",7,6,2,17],["x-label3",17,19,23,9],["x-label3",12,4,11,18]]

For a visual representation and implementation example, check out this JSFiddle demonstration.

UPDATE: Below is a sample C# code snippet to convert your line data from row-based to columnar format. Adjust the number of lines as needed and paste the resulting Json into the provided JSFiddle example for visualization:

var numberOfLines = 7; // Specify the number of lines desired.
var xAxisHeadings = new object[] { "NOT USED", "Original Documents", "Filing of Entries", "Assessment of Duties", "Payment of Duties", "Releasing", "Gate Pass", "Delivery" };
var lines = new List<object[]>();
lines.Add(xAxisHeadings);

// Generate data for each line based on multiples of the line number
for (int i=0; i<numberOfLines; i++)
{
    lines.Add(new object[] { "L" + i, 1 * (i+1), 2 * (i+1), 3 * (i+1), 4 * (i+1), 5 * (i+1), 6 * (i+1), 7 * (i+1) });
}

var answer = new List<object>{};
for (int i=0; i<lines.Count; i++)
{
    var x = lines.Select(a => a[i]).ToArray();
    answer.Add(x);
}

var json = Newtonsoft.Json.JsonConvert.SerializeObject(answer);

The resulting Json is as follows:

[["NOT USED","L0","L1","L2","L3","L4","L5","L6"],["Original Documents",1,2,3,4,5,6,7],["Filing of Entries",2,4,6,8,10,12,14],["Assessment of Duties",3,6,9,12,15,18,21],["Payment of Duties",4,8,12,16,20,24,28],["Releasing",5,10,15,20,25,30,35],["Gate Pass",6,12,18,24,30,36,42],["Delivery",7,14,21,28,35,42,49]]

By integrating this into the existing JSFiddle example, you can visualize the updated data with this revised JSFiddle demo.

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

Showing a div element with the power of JavaScript

I want to enhance the accessibility of my website for users who do not have JavaScript enabled. Content that will be visible if the user has JavaScript enabled. Content visible when JavaScript is disabled. By default, DisableJS is set to Display:none; ...

Incomplete Loading of Google Maps

Let me clarify that the solutions I have come across so far have not been successful. I am attempting to display a modal alert with a basic Google Maps integration. Problem: Google Maps does not load completely. Snippet from my .js file: var map; functi ...

Silky animations in kinetic.js (html5 canvas)

I am seeking a better grasp on kinetic.js animation. Recently, I came across a tutorial at . After experimenting with the code provided, I managed to create an animation that positions my rectangle at x coordinate 100. However, I am struggling to achieve s ...

Generate Material UI sidebar components that are positioned above all other components

I am currently working on a sidebar component using the Material UI Drawer component. I am looking to add components that align side by side with the sidebar, similar to the green box shown in the image below. After attempting to code this, I ended up wi ...

How to style TextInput to display dollar amounts when using onChangeText and Redux in React Native

Struggling to format number input in a TextInput using the onChangeText function in React Native with Redux. Tried using .toFixed(2) function, but encountering an issue where it interprets the next digit as the first decimal and rounds back to 0 due to Re ...

What is causing the button within my ExtJS grid to display as "[object Object]"?

Within an ExtJS grid, I am facing a scenario where I need to display a button in a specific column when the content of a cell meets certain criteria. To achieve this, I define the column with the button using a rendering function as shown below: { he ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

The function $.ajax({}) is not recognized in the Django framework

I have been searching for a solution to this specific problem, but none of the related questions I found were able to help. There must be another reason why it's not working, but I'm finding it difficult to pinpoint the issue. Here is the code sn ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...

The React Component is limited to updating once

Exploring the React Native code below: import React from 'react'; import {Text, View, StyleSheet, Button} from 'react-native'; export default class Target extends React.Component { constructor(props){ super(props); ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...

Detecting Pixel Colors Across Multiple Overlapping Canvases

I have a challenge with multiple canvas elements on my webpage. I am trying to retrieve the pixel color of all overlapping canvas elements when they are stacked on top of each other. Let me illustrate with an example below. In this scenario, I am attempt ...

display a visual element within a function using reasoning

I am trying to display an image based on a specific condition in my code, for example: if(x==1) { showImage }. However, I am facing an issue where the web content is not displayed until the image is fully loaded. What I want is for the image to appear smoo ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

Achieving top-tier efficiency in segmenting items within an array of objects

Looking for a way to decrease the size of an array directly on my NodeJS server's memory. I aim to optimize network traffic by sending only the essential 'header' details of each object within the array. The current array on the server look ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

Troubleshooting Block-scoped errors on Heroku using Node.js and Express

Currently, I am working with node.js and express on the Heroku platform. While working on the route file, I encountered an issue when using the let keyword. The error message displayed was: SyntaxError: Block-scoped declarations (let, const, function, cla ...