如何更改形状的可见性?假设我的情节中有5个形状,我想隐藏第一个。
var update = {
'shapes[0]': {
'visible': false
}
}
Plotly.relayout(graphElement, update);
我尝试了这个,但它创建了一个新的(不可见的形状)并将其放在形状的开头而不是更新。
答案 0 :(得分:0)
你几乎拥有它,根据Plotly.js Function Reference
中的函数引用,我们应该如下编写对象属性。
// update only values within nested objects
var update = {
title: 'some new title', // updates the title
'xaxis.range': [0, 5], // updates the xaxis range
'yaxis.range[1]': 15 // updates the end of the yaxis range
};
Plotly.relayout(graphDiv, update)
正如您所看到的,永远不会有超过1的深度。所以我们需要像这样更新那个特定的形状。
var update = {
'shapes[1].visible': false
}
Plotly.relayout(div, update);
在这里,我们选择数组shapes
的第一个对象,选择visible属性并将值设置为false
。
请参阅以下工作示例,并告知您的问题是否已完全解决。
var d3 = Plotly.d3
function normal_array(mean, stddev, size) {
var arr = new Array(size),
i;
// from https://bl.ocks.org/nrabinowitz/2034281
var generator = (function() {
return d3.random.normal(mean, stddev);
}());
for (i = 0; i < arr.length; i++) {
arr[i] = generator();
}
return arr;
}
var x0 = normal_array(2, 0.45, 300);
var y0 = normal_array(2, 0.45, 300);
var x1 = normal_array(6, 0.4, 200);
var y1 = normal_array(6, 0.4, 200)
var x2 = normal_array(4, 0.3, 200);
var y2 = normal_array(4, 0.3, 200);
var data = [{
x: x0,
y: y0,
mode: 'markers'
}, {
x: x1,
y: y1,
mode: 'markers'
}, {
x: x2,
y: y2,
mode: 'markers'
}, {
x: x1,
y: y0,
mode: 'markers'
}];
var layout = {
margin: {
t: 10,
r: 10,
b: 20,
l: 10
},
shapes: [{
type: 'circle',
xref: 'x',
yref: 'y',
x0: d3.min(x0),
y0: d3.min(y0),
x1: d3.max(x0),
y1: d3.max(y0),
opacity: 0.2,
fillcolor: 'blue',
line: {
color: 'blue'
}
},
{
type: 'circle',
xref: 'x',
yref: 'y',
x0: d3.min(x1),
y0: d3.min(y1),
x1: d3.max(x1),
y1: d3.max(y1),
opacity: 0.2,
fillcolor: 'orange',
line: {
color: 'orange'
}
},
{
type: 'circle',
xref: 'x',
yref: 'y',
x0: d3.min(x2),
y0: d3.min(y2),
x1: d3.max(x2),
y1: d3.max(y2),
opacity: 0.2,
fillcolor: 'green',
line: {
color: 'green'
}
},
{
type: 'circle',
xref: 'x',
yref: 'y',
x0: d3.min(x1),
y0: d3.min(y0),
x1: d3.max(x1),
y1: d3.max(y0),
opacity: 0.2,
fillcolor: 'red',
line: {
color: 'red'
}
}
],
height: 400,
width: 480,
showlegend: false
}
Plotly.newPlot('myDiv', data, layout);
$('.toggle').on("click", function(e) {
e.preventDefault();
var div = document.getElementById('myDiv');
var update = {
'shapes[1].visible': false
}
Plotly.relayout(div, update);
});
.toggle {
position: fixed;
top: 0px;
left: 0px;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="myDiv" style="width: 480px; height: 400px;">
<!-- Plotly chart will be drawn inside this DIV -->
</div>
<button class="toggle">Hide First Trace</button>
<script>
<!-- JAVASCRIPT CODE GOES HERE -->
</script>
</body>