Home Forums Chart Support Dynamic chart extra lines being added

Dynamic chart extra lines being added

Viewing 10 posts - 1 through 10 (of 10 total)
  • #21790

    I am running into an issue whenever my chart renders. I am using a line graph that pulls json data from another file, this updates dynamically.

    The issue dynamic line graph issue as shown is that the last point seems to draw a line to the first point.

    Here is the code I am using. Also the JSON is like this https://api.myjson.com/bins/14imny

    <!DOCTYPE HTML>
        <html>
        <head>  
    <style>
    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #333;
    }
    
    li {
        float: left;
        border-right:1px solid #bbb;
    }
    
    li:last-child {
        border-right: none;
    }
    
    li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }
    
    li a:hover:not(.active) {
        background-color: #111;
    }
    
    .active {
        background-color: #004299;
    }
    </style>
    </head>
    <meta charset="utf-8"/>
    <script type="text/javascript">
    window.onload = function() {
    	var dataPoints = [];
    	var chart;
    	$.getJSON('JSON.php', function(data) {  
    		$.each(data, function(key, value){
    			dataPoints.push({x:(value)["x"], y:(value["y"])});
    		});
    		chart = new CanvasJS.Chart("chartContainer",{
    			title:{
    				text:"Live Chart with dataPoints from External JSON"
    			},
    			zoomEnabled: true,
        	axisX:{
    			scaleBreaks:{
    				autoCalculate: true,
    				maxNumberOfAutoBreaks: 5,
    				collapsibleThreshold: "15%"
    			},
    		},
        	zoomType: "xy",
        	//backgroundColor: "#bdcfed",
        	animationEnabled: true,
       		animationDuration: 5000,
        	exportEnabled: true,
        	theme: "dark1",
    			data: [{
    			showInLegend: true,
        		legendText: "Temperature",
        		markerType: "circle",
                markerSize: "3",
                markerColor: "red",
    			xValueType: "dateTime",
        		xValueFormatString: "YYYY-MM-DD HH:mm:ss",
        		toolTipContent: "x:{x}, y: {y}",
        		type: "line",
    				dataPoints : dataPoints,
    			}]
    		});
    		chart.render();
    		updateChart();
    	});
    	function updateChart() {
    	$.getJSON('JSON.php', function(data) {
    		$.each(data, function(key, value) {
    			dataPoints.push({
    			x:(value["x"]),
    			y:(value["y"]),
    			
    			});
    		});
    		
    		chart.render();
    		setTimeout(function(){updateChart()}, 5000);
    	});
    	}
    }
    </script>
    <script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
    </head>
    <body>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    </body>
    </html>
    #21805

    @Vulpe,

    Every time you call update chart, the new dataPoints along with the complete set of existing dataPoints gets added to the chart. Hence, the complete graph will be drawn repeatedly on top of each other. Clearing the existing dataPoints before adding the next set(complete set) of dataPoints should work fine in your case. Please take a look at this jsfiddle.

    __
    Priyanka M S
    Team CanvasJS

    #21821

    I altered my code to match the jsfiddle you linked but now my graph will no longer update in real time.

    #21835

    @Vulpe,

    You can observe this behaviour because the JSON data you are providing to updateChart() method is same as the JSON data provided while rendering chart for the first time. Can you kindly create a jsfiddle that has JSON data updating dynamically, so that we can look into the code, understand your scenario better and help you out?

    __
    Priyanka M S
    Team CanvasJS

    #21838

    I’m not sure that would be possible as the JSON.php file I use to get my json data pulls it straight from a local hosted database.
    And the code I posted above updates data dynamically from the database.

    #21839

    I don’t know if its of any use to you but here is the code the code that gets my data for me

    <?php
         
        $dataPoints = array();
        
        try{
             // Creating a new connection.
            
            $link = new \PDO(   'mysql:host=192.168.0.89;dbname=light;charset=utf8mb4', 
                                'Jack', 
                                'Password', 
                                array(
                                    \PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                    \PDO::ATTR_PERSISTENT => false
                                )
                            );
        	
            $handle = $link->prepare('select BTime, TSensor2 from bottomsensors'); 
            $handle->execute(); 
            $result = $handle->fetchAll(\PDO::FETCH_OBJ);
        		
            foreach($result as $row){
                array_push($dataPoints, array("x"=> strtotime($row->BTime)*1000, "y"=> $row->TSensor2));
            }
        	$link = null;
        }
        catch(\PDOException $ex){
            print($ex->getMessage());
        }
        echo json_encode($dataPoints, JSON_NUMERIC_CHECK);
    ?>
    #21843

    I managed to solve the problem.

    I changed the updateChart function as according to this forum post https://canvasjs.com/forums/topic/how-to-update-chart-data-every-second/

    Thank you for the help.

    #21856

    @Vulpe,

    Glad that you figured it out.

    __
    Priyanka M S
    Team CanvasJS

    #26153

    please give me ur sample code please, That same problem is bothering me also.

    This is my code :

    ———————-

    <%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
    <%@ page import="java.util.*" %>
     
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
    <script type="text/javascript">
    
    var dataPoints = [];
    var chart;
    $.getJSON('http://localhost:8080/SpringREST/rasp/json', function(data) {  
      $.each(data, function(key, value){
        dataPoints.push({x:(value)["creation_time"], y:Number(value["temp"])});
      });
      chart = new CanvasJS.Chart("chartContainer",{
        title:{
          text:"Live Chart with dataPoints from External JSON"
        },
        zoomEnabled: true,
        axisX:{
           scaleBreaks:{
            autoCalculate: true,
            maxNumberOfAutoBreaks: 5,
            collapsibleThreshold: "15%"
          },
        },
        zoomType: "xy",
        //backgroundColor: "#bdcfed",
        animationEnabled: true,
        animationDuration: 5000,
        exportEnabled: true,
        theme: "dark1",
        data: [{
          showInLegend: true,
          legendText: "Temperature",
          markerType: "circle",
          markerSize: "3",
          markerColor: "red",
          xValueType: "dateTime",
          xValueFormatString: "YYYY-MM-DD HH:mm:ss",
          toolTipContent: "x:{x}, y: {y}",
          type: "line",
          dataPoints : dataPoints,
        }]
      });
      chart.render();
      updateChart();
    });
    
    function updateChart() {
      $.getJSON('http://localhost:8080/SpringREST/rasp/json', function(data) {
      	//dataPoints = [];
        $.each(data, function(key, value) {
            dataPoints.push({
                x:(value["creation_time"]),
                y: Number(value["temp"]),
    
              });
        });
        console.log(chart.options)
        chart.render();
      });
    }
    
    setTimeout(function(){updateChart()}, 1000);
    
    </script>
    </head>
    <body>
    <br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
    <div id="chartContainer" style="height: 360px; width: 100%;"></div>
    </body>
    </html>
    #26175

    @shyamcanvas1992,

    Please take a look at this Gallery example for working code on rendering chart with data from JSON.

    setTimeout method calls a function or evaluates an expression after a specified number of milliseconds (only once) whereas setInterval method calls a function or evaluates an expression at specified intervals (in milliseconds). Changing setTimeout to setInterval should work fine in this case.

    If you are still facing the issue, kindly share sample project reproducing the issue along with sample JSON over Google-Drive or Onedrive so the we can look into the code, run it locally to understand the scenario better and help you resolve.


    Shashi Ranjan
    Team CanvasJS

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.