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

标签 javascript plotly

我想在页面上添加和删除带有按钮的图表。 我必须将布局和数据作为 Json 传递给plotly.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>

关于javascript - 使用 Plotly.js 动态创建/删除/重新设计图形的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104292/

相关文章:

javascript - 使用ajaxForm提交表单而不刷新页面

javascript - 从数组中删除空字符串

python - 将多个表添加到 plotly plot

python - 用许多数据点绘制散点图会产生模糊的 svg

javascript - d3.js 超出最大调用堆栈大小错误

javascript - 对多维数组中的 RGB 颜色进行排序

r - Plotly scaleY 不适用于子图行

javascript - R Shiny + plotly : change color of a trace with javascript without affecting markers and legend in multiple plots

javascript - 正则表达式以@符号开头

Python Plotly 登录错误