Search code examples
javascriptjqplot

Redrawing graph, jpPlot


I'm trying to make a graph that produces random lines and keeps redrawing every 5 seconds. It does redraw but the old scales are overlapped. Is there a way to remove the old graphs before redrawing new graphs?

HTML

<div id="pointg"></div> 

JavaScript

var k=0;//if graph() is first time

function graph(){   
    var ga=[];
    for(var j=0;j<11;j++){
        ga[j] = Math.random() *20;
    }
        $(function () {
    $.jqplot('pointg', [[[0, ga[0]], [2, ga[1]], [4, ga[2]], [6, ga[3]], [8, ga[4]],[10, ga[5]],[12, ga[6]],[14, ga[7]],[16, ga[8]],[18, ga[9]],[20, ga[10]],[22, ga[11]] ]],{
        axes: {
            xaxis: {
                ticks: [ '0', '5', '10', '15', '20' ],
            },
            yaxis: {
                ticks: [ '0', '5', '10', '15', '20' ],
            }
        },
        animate: true,
        seriesDefaults: {
                color: '#ffffff',
                markerOptions: {
                    size: 6
                }

        },
        grid: {
            background: '#000000'
        },
    });
});
    if(k!=0){       
    //remove?   
    }
k++;
;}

graph();
setInterval('graph()',5000);

Solution

  • Do you mean that the axis tick labels are drawn on top of each other like this? enter image description here

    You can use the destroy() method to destroy the existing plot before drawing another one. To do this, you'll need to assign your jqplot to a global variable:

    var plot;
    
    function graph(){
        ...  
        plot = $.jqplot('pointg', [...],{
            axes: {
                ...
            },
            animate: true,
            seriesDefaults: {
                ...
            },
            grid: {
                ...
            },
        });
    

    and before you call the $.jqplot(...), ensure you check and destroy the existing plot:

    if (plot) {
        plot.destroy();
    }
    

    A full example can be found here. It will result in the following where the axis tick labels are not rendered on top of each other:

    enter image description here