2

I want to add and delete graphs with buttons on my page. I have to pass layout, and data as Json to the plotly.plot() function. How can i do this dynamically?

Example code from reference :

var trace1 = {
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  type: 'scatter'
};

var trace2 = {
  x: [1, 2, 3, 4],
  y: [16, 5, 11, 9],
  type: 'scatter'
};

var data = [trace1, trace2];

var layout = {
  width: 500,
  height: 500
};

Plotly.newPlot('myDiv', data,layout);

i receive my data via ajax from a database.

function getTrace_data(x,y) {
  $.ajax({
    type: "GET",
    url: "get.php?action=data&x="+x+"&y="+y
    dataType: "json",
    success: function(data){
      drawGraph(data);
    },
    error: function(error){ 
      console.log(error);
    }  
  });
}

function drawGraph(data)
{
  var trace1 = {
    x: data.x,
    y: data.y,
    type: 'scatter'
  };

  var layout = {
    width: 500,
    height: 500
  };
  Plotly.newPlot('myDiv', data,layout);
}

Now i can draw a graph, but how should i change the type of the graph dynamically? or layout options?

1 Answer 1

2

You can just overwrite the existing graph with a new one and dynamically change the layout of your graph with a few variables, see the snippet below. Just assume the buttons are different AJAX calls.

function changeGraph(graphType) {
    var traces = [];
    var graph_types = [];
    var myDiv = document.getElementById("mydiv");
    switch (graphType) {
    case 1:
        graph_types.push("scatter");
        graph_types.push("bar");
        break;
    case 2:
        graph_types.push("bar");
        graph_types.push("bar");
        break;
    default:
        graph_types.push("scatter");
        graph_types.push("scatter");
    }
    traces.push({
        x: [1, 2, 3, 4],
        y: [10, 15, 13, 17],
        type: graph_types[0]
    });

    traces.push({
        x: [1, 2, 3, 4],
        y: [16, 5, 11, 9],
        type: graph_types[1]
    });

    var layout = {
        width: 500,
        height: 500
    };

    Plotly.newPlot(myDiv, traces, layout);
}

document.getElementById("button0").addEventListener("click", function () {
    changeGraph(0);
});
document.getElementById("button1").addEventListener("click", function () {
    changeGraph(1);
});
document.getElementById("button2").addEventListener("click", function () {
    changeGraph(2);
});

document.getElementById("button0").click();
<script src=https://cdn.plot.ly/plotly-latest.min.js></script>
<div id="mydiv"></div>

<button id="button0">Scatter only</button>
<button id="button1">Bar&Scatter</button>
<button id="button2">Bars only</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.