我正在创建一系列效果很好的plotly.js 形状。我根据形状类型添加了 'custType' : '1' 或 'custType' : '2' 的自定义数据属性。每种形状类型的数量不会一致,因此我需要能够动态更新可见性。
我已经尝试过了...没有效果
var update = [];
for(x=0; x<data.layout.shapes.length; x++){
if(data.layout.shapes[x].custType == '1'){
update.push({'shapes[' + x + '].visible':false})
}
}
Plotly.relayout('main', update);
最佳答案
update
必须是一个对象而不是数组,例如
{
"shapes[0].visible": false,
"shapes[1].visible": false
}
请参阅下面的代码片段。
const trace = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter'
};
const data = [trace];
const layout = {
shapes: [
{
type: 'rect',
x0: 1,
x1: 2,
y0: 10,
y1: 12,
fillcolor: '#d3d3d3',
line: {
width: 0
}
},
{
type: 'rect',
x0: 3,
x1: 4,
y0: 12,
y1: 14,
fillcolor: '#d3d3d3',
line: {
width: 0
}
}
]
}
Plotly.newPlot('myDiv', data, layout);
function update() {
const update = {};
for(let i = 0; i < layout.shapes.length; i++){
update['shapes[' + i + '].visible'] = false;
}
Plotly.relayout('myDiv', update);
}
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
<button type="button" onClick="update()">Update</button>
</body>
关于javascript - 在 Plotly.js 中动态切换形状的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64016308/