What is the best way to create a dynamic graph in amcharts during runtime?

Below is the code for Multiple Value Axes:

In this code, we aim to display a graph using dynamically generated random data. When executed, nothing will happen.

<script>
var chart;
var chartData = [];
// generate some random data within a different range
function generateChartData() {
    var firstDate = new Date();
    firstDate.setDate(firstDate.getDate() - 50);
    var v = [];
    var a = [];
    for (var i = 0; i < 50; i++) {
        var newDate = new Date(firstDate);
        newDate.setDate(newDate.getDate() + i);}

     for (var j = 1; j < 4; j++) {   
        v[j] = Math.round(Math.random() * 40 *j) + 100;
         chartData.push({
            date: newDate,
            a + j.toString():v[j]
          // a + j =stringValue-0;
          // var a[j]:v[j],       
        });   
     }   
    }
}
// this method gets called when the chart is initialized as it listens for "dataUpdated" event
function zoomChart() {
    // different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
    chart.zoomToIndexes(10, 20);
}
// create the chart
AmCharts.ready(function() {
    // generate some random data first
    generateChartData();

    // SERIAL CHART    
    chart = new AmCharts.AmSerialChart();
    chart.marginTop = 0;
    chart.autoMarginOffset = 5;
    chart.pathToImages = "http://www.amcharts.com/lib/images/";
    chart.zoomOutButton = {
        backgroundColor: '#000000',
        backgroundAlpha: 0.15
    };
    chart.dataProvider = chartData;
    chart.categoryField = "date";
    // listen for "dataUpdated" event (fired when chart is inited) and call zoomChart method when it happens
    chart.addListener("dataUpdated", zoomChart);
    // AXES
    // category                
    var categoryAxis = chart.categoryAxis;
    categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
    categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to DD
    categoryAxis.dashLength = 2;
    categoryAxis.gridAlpha = 0.15;
    categoryAxis.axisColor = "#DADADA";
    // first value axis (on the left)
    var valueAxis1 = new AmCharts.ValueAxis();
    valueAxis1.axisColor = "#FF6600";
    valueAxis1.axisThickness = 2;
    valueAxis1.gridAlpha = 0;
    chart.addValueAxis(valueAxis1);
    // second value axis (on the right) 
    var valueAxis2 = new AmCharts.ValueAxis();
    valueAxis2.position = "right"; // this line makes the axis appear on the right
    valueAxis2.axisColor = "#FCD202";
    valueAxis2.gridAlpha = 0;
    valueAxis2.axisThickness = 2;
    chart.addValueAxis(valueAxis2);
    // third value axis (on the left, detached)
    valueAxis3 = new AmCharts.ValueAxis();
    valueAxis3.offset = 50; // this line makes the axis appear detached from plot area
    valueAxis3.gridAlpha = 0;
    valueAxis3.axisColor = "#B0DE09";
    valueAxis3.axisThickness = 2;
    chart.addValueAxis(valueAxis3);
    var  graph = [];
    var v ;
for (var j = 1; j < 4; j++) 
{   
    graph[j] = new AmCharts.AmGraph();
    graph[j].valueAxis = valueAxis1; // we have to indicate which value axis should be used
    graph[j].title = "red line";
    v = a + j.toString();
    graph[j].valueField = v;
    graph[j].bullet = "round";
    graph[j].hideBulletsCount = 30;
    chart.addGraph(graph[j]);
}
    // CURSOR
    var chartCursor = new AmCharts.ChartCursor();
    chartCursor.cursorPosition = "mouse";
    chart.addChartCursor(chartCursor);
    // SCROLLBAR
    var chartScrollbar = new AmCharts.ChartScrollbar();
    chart.addChartScrollbar(chartScrollbar);
    // LEGEND
    var legend = new AmCharts.AmLegend();
    legend.marginLeft = 110;
    chart.addLegend(legend);

    // WRITE
    chart.write("chartdiv");
});
</script>
<body>
  <div id="chartdiv" style="width: 640px: hieght: 400px: overflow: hidden: text-align: left;">
  </div>
</body>

Answer №1

It appears that you are interested in generating 4 graphs with random values.

If this is the case, there are several issues in your code:

The values for each graph need to be combined into a single data point for each category. This means creating one object per category:

[
  {
    date: '2015-01-01',
    value1: 100,
    value2: 200,
    value3: 300,
    value4, 400
  },
  {
    date: '2015-01-02',
    value1: 101,
    value2: 201,
    value3: 302,
    value4, 404
  },
  // etc.
]

To achieve this, you should create an item with a date component, generate values for each graph, add them to the same object, and then push that object into the chart data array.

function generateChartData() {
  var firstDate = new Date();
  firstDate.setDate(firstDate.getDate() - 50);
  for (var i = 0; i < 50; i++) {
    var newDate = new Date(firstDate);
    newDate.setDate(newDate.getDate() + i);
    var item = {
      date: newDate
    };
    for (var j = 1; j < 4; j++) {
      item[j.toString()] = Math.round(Math.random() * 40 * j) + 100;;
    }
    chartData.push(item);
  }
}

The process of adding actual graph objects remains the same. Simply assign valueField to the same key as specified in the data:

  var v;
  for (var j = 1; j < 4; j++) {
    graph[j] = new AmCharts.AmGraph();
    graph[j].valueAxis = valueAxis1; // indicate which value axis to use
    graph[j].title = "red line";
    v = j.toString();
    graph[j].valueField = v;
    graph[j].bullet = "round";
    graph[j].hideBulletsCount = 30;
    chart.addGraph(graph[j]);
  }

Below is the complete functioning code snippet:

 // Entire JavaScript code block
 
#chartdiv {
  width: 100%;
  height: 500px;
  font-size: 11px;
}
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/serial.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></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

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

A guide to transferring modules between component files in JavaScript

My query pertains to the handling of imports in web pages. When a file is imported into another, do the declarations and imports from the imported file become available in the file where it is being imported? A suggestion was made for me to import a compo ...

Guide on showcasing all entries in the database within the body section of an HTML table

Looking to showcase data from a table inside the body section of an html page This is the code I've been working on: <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vi ...

An easy way to create an input field after clicking a button

When I try to add a field on Button Click, the default field is not showing and does not get added upon button click I have put in my best effort but I cannot figure out what the problem is. I have added functions and used Math to generate a unique id. Th ...

"Discover the process of transforming HTML, CSS, and script files into a cohesive JavaScript format

I have developed a unique web chat widget from scratch using HTML, CSS, JavaScript, and AJAX calls. Now, my goal is to convert it into a script that can be easily embedded in any other websites or webpages. Similar to how third-party widgets work, users sh ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

Tips for directing attention to a specific row with an input field in JavaScript

I duplicated a table and added an input field for users to search or focus on a specific row. However, there are two issues: When a user enters a row number, the table displays the wrong row - for example, if the user enters 15, the table shows row number ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Exploring the history and present state of Vue lifecycle hooks

Is there a way to access previous and current data in the updated lifecycle hook in Vue, similar to React? I want to be able to scroll a list of elements to the very bottom, but for this I need: The already rendered updated DOM (to calculate the scroll) ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Map on leaflet not showing up

I followed the tutorial at http://leafletjs.com/examples/quick-start/ as instructed. After downloading the css and js files to my local directory, I expected to see a map but all I get is a gray background. Can anyone advise me on what might be missing? T ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

Is it possible to extract all parameters, including nested or within arrays, from a Swagger File using Node.js?

Looking for a method to extract and interpret data such as parameters from a Swagger file. Specifically, I am working with the Petstore Swagger API ( ). The definitions within the file contain references to other components, like parameters. One example ...

Unable to display items in controller with AngularJS

I am facing an issue with displaying a slider using ng-repeat in my AngularJS code. The pictures and other elements defined in the controller are not showing up on the page. Here is the JavaScript code snippet: angular.module('starter', []) .co ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

How can I implement Google Analytics Event tracking for all <audio> tags using Javascript?

I am looking to implement a Google Analytics Event for all audio tags on my website. Currently, I have a script that targets audio tags with a specific class: <script> /* a test script */ $(function() { // Execute function when any element with t ...