我想在页面上添加和删除带有按钮的图表。 我必须将布局和数据作为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);
}
现在我可以绘制图形了,但是我应该如何动态更改图形的类型?或布局选项?
答案 0 :(得分:2)
您可以使用新图表覆盖现有图表,并使用一些变量动态更改图表的布局,请参阅下面的代码段。假设按钮是不同的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>
&#13;