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

Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side. Is it possible to position an element absolutely ...

Troubleshooting JavaScript: Dealing with JSON Import Issues Involving Arrays of Objects

I'm encountering an issue while trying to import a JSON file that contains an array of blog-posts. Although all the data from the JSON file is successfully imported, I am facing troubles with accessing the Array of objects (edges). This specific code ...

How can you leverage Symfony to iterate through a JSON array efficiently?

After selecting a user, I am attempting to display a list of contracts. To achieve this, I have written the following query: /** * @param $firstname * @param $lastname * @return mixed * @throws DBALException */ public function getListPerUser($firs ...

Display or conceal <ul>'s using JavaScript when the mouse enters or leaves

I'm encountering an issue with a basic JavaScript function. The goal is to toggle the dropdown menu on my website when the mouse hovers over or leaves the menu. The problem arises because my script is triggered by the ul tags within my menu, and I ha ...

The Vue production build displays a blank page despite all assets being successfully loaded

After running npm run build, I noticed that my vue production build was displaying a blank page with the styled background color from my CSS applied. Looking at the page source, I saw that the JS code was loading correctly but the content inside my app d ...

What is the method for altering the color of the webkit-slider-thumb using JavaScript?

I am looking to adjust the color of an input range using JavaScript instead of CSS. Can someone help me with this request? Current CSS Code: input[type='range']::-webkit-slider-thumb { -webkit-appearance: none; background: goldenrod !importa ...

When attempting to use JSON.parse, it returns an undefined value

When using PHP to create JSON data and retrieving it through AJAX, why does JSON.parse return an "undefined" object? PHP CODE $emparray = array(); while($row =mysqli_fetch_assoc($result)) { $emparray[] = $row; } echo json_encode($emparray); AJ ...

adding numerous items to an array using JavaScript

How can I add multiple objects to an array all at once? router.post(`/products`, upload.array("photos" , 10), async (req, res) => { console.log(res); try { let product = new Product(); req.files.forEach(file => { product.p ...

Typescript enhances Solid JS by using the "as" prop and the "component" prop

Hey there, I've been experimenting with solid-js lately and I'm facing a challenge integrating it with typescript. My objective is to make my styling more modular by incorporating it within my components. type RelevantTags = Exclude<keyof ...

Discovering a specific property of an object within an array using Typescript

My task involves retrieving an employer's ID based on their name from a list of employers. The function below is used to fetch the list of employers from another API. getEmployers(): void { this.employersService.getEmployers().subscribe((employer ...

Setting up protected routes using react-router-dom version 6

When a visitor navigates to / (home), I want them to be redirected to /connexion" if they are not connected. To achieve this, I have implemented Private routes that work well. Now, I need to create the logic that will handle the redirection based on t ...

Converting large numbers (exceeding 53 bits) into a string using JavaScript

I have a REST service that returns JSON. One of the properties in the JSON contains a very large integer, and I need to retrieve it as a string before Javascript messes it up. Is there a way to do this? I attempted to intercept every response using Angular ...

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

Checked boxes in the React dynamic checkbox list are not being marked

Can you please assist me with the following issue: I am in the process of creating a nested dynamic list of checkboxes for selecting companies and groups within those companies. Upon investigation, I have come up with the following code snippet const [ch ...

The script ceases to function once the page is loaded from a JSON file

I'm facing an issue on my shopping website where the items and products are loaded from a JSON file. The problem is that once the page has loaded, the script fails to work properly. If the items take a little longer to load on the page, the script doe ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

How come I am getting the desired section from my split string only after running the function twice?

I've been working on a function that retrieves data from a form and sends it to a POST request, which in turn sends it to my MongoDB database. The following code snippet showcases the process of uploading an image to IPFS, extracting the IPFS hash fro ...

Saving JSON Data into my HTML document

Currently, I am in the process of learning about API's at school which means my knowledge of jQuery is quite limited. However, I have a specific task that involves making an API call and using the retrieved information. Recently, I conducted an ajax ...