使用Plotly.js动态创建/删除/重新设计图形的最佳方式

Best way of create/delete/restyle graph dynamically with Plotly.js?

本文关键字:图形 方式 最佳 js Plotly 动态 创建 删除 使用      更新时间:2023-09-26

我想在我的页面上添加和删除带有按钮的图形。我必须将布局和数据作为Json传递给plot .plot()函数。我如何动态地做到这一点?

参考资料中的示例代码:

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);

我通过ajax从数据库接收数据。

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);
}

现在我可以画一个图形,但是我应该如何动态地改变图形的类型?或者布局选项?

您可以用一个新图形覆盖现有图形,并使用几个变量动态更改图形的布局,参见下面的代码片段。假设按钮是不同的AJAX调用。

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>