我有几个要成对比较的数字列表。我尝试使用Plotly制作散点图并添加按钮,我希望能够在x或y轴上更改列表。
使用WTForms Doc,我设法创建了情节和按钮。但是,当我选择另一个列表时,轴不会更新。
这是我的示例代码:
import plotly
from plotly import graph_objs as go, offline as po, tools
po.init_notebook_mode()
import numpy as np
l1 = list(np.random.randint(100, size=100))
l2 = list(np.random.rand(100))
l3 = list(np.random.randint(100, size=100))
# Create figure
fig = go.Figure()
# Add scatter
fig.add_trace(go.Scatter(
x=l1,
y=l1,
mode = 'markers'
)
)
# Add drowdowns
button_layer_1_height = 1.15
fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
buttons=list([
dict(
args=["x", l1],
label="L1",
method="restyle"
),
dict(
args=["x", l2],
label="L2",
method="restyle"
),
dict(
args=["x", l3],
label="L3",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.02,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
go.layout.Updatemenu(
buttons=list([
dict(
args=["y", l1],
label="L1",
method="restyle"
),
dict(
args=["y", l2],
label="L2",
method="restyle"
),
dict(
args=["y", l3],
label="L3",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.15,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
go.layout.Annotation(text="x", x=0, xref="paper", y=1.08, yref="paper",
align="left", showarrow=False),
go.layout.Annotation(text="y", x=0.13, xref="paper", y=1.08,
yref="paper", showarrow=False),
])
fig.show()
答案 0 :(得分:1)
在args
中,您的列表(例如L1)需要成为列表的元素,而不仅仅是列表本身。因此,只需将所有args=["x", l1]
更改为args=["x", [l1]]
,您就可以开始了!听起来好得令人难以置信?这是一些证据
首次运行时的图:
为x选择L2时的图:
为y选择L3时的图:
这是您编辑的代码:
import plotly
from plotly import graph_objs as go, offline as po, tools
po.init_notebook_mode()
import numpy as np
l1 = list(np.random.randint(100, size=100))
l2 = list(np.random.rand(100))
l3 = list(np.random.randint(100, size=100))
# Create figure
fig = go.Figure()
# Add scatter
fig.add_trace(go.Scatter(
x=l1,
y=l1,
mode = 'markers'
)
)
# Add drowdowns
button_layer_1_height = 1.15
fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
buttons=list([
dict(
args=["x", [l1]],
label="L1",
method="restyle"
),
dict(
args=["x", [l2]],
label="L2",
method="restyle"
),
dict(
args=["x", [l3]],
label="L3",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.02,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
go.layout.Updatemenu(
buttons=list([
dict(
args=["y", [l1]],
label="L1",
method="restyle"
),
dict(
args=["y", [l2]],
label="L2",
method="restyle"
),
dict(
args=["y", [l3]],
label="L3",
method="restyle"
),
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.15,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
go.layout.Annotation(text="x", x=0, xref="paper", y=1.08, yref="paper",
align="left", showarrow=False),
go.layout.Annotation(text="y", x=0.13, xref="paper", y=1.08,
yref="paper", showarrow=False),
])
fig.show()