javascript - 在 Plotly.js 中动态切换形状的可见性

标签 javascript plotly.js

我正在创建一系列效果很好的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/

相关文章:

javascript - 从 Node.js 中的模块导出函数的语法是什么?

javascript - 使用本地存储保存自定义列表显示中的更改

javascript - Bootstrap 卡片中的响应式 PlotlyJS 图表

javascript - 没有 onScroll 的滚动速度更快?

Javascript/Jquery/Moment.js 计算两个日期之间的天数

javascript - 为什么在通过 javascript 添加时 css 转换会回到原来的位置?

python - 在 Plotly 3.0 中设置图例文本颜色

javascript - 绘图仪动态

javascript - 如何使 Plotly 绘图遵循父容器的大小?