【发布时间】:2021-09-16 14:13:48
【问题描述】:
我试图在一个循环中定义所有 y 轴。 kwargs** 是最好的方法(using a loop to define multiple y axes in plotly)还是我可以使用 globals()?我无法让我的方法发挥作用。我宁愿只为布局运行一个循环,而不是为跟踪。感谢您的帮助
原始示例
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6],
name="yaxis1 data"
))
fig.add_trace(go.Scatter(
x=[2, 3, 4],
y=[40, 50, 60],
name="yaxis2 data",
yaxis="y2"
))
fig.add_trace(go.Scatter(
x=[4, 5, 6],
y=[40000, 50000, 60000],
name="yaxis3 data",
yaxis="y3"
))
fig.add_trace(go.Scatter(
x=[5, 6, 7],
y=[400000, 500000, 600000],
name="yaxis4 data",
yaxis="y4"
))
# Create axis objects
fig.update_layout(
xaxis=dict(
domain=[0.3, 0.7]
),
yaxis=dict(
title="yaxis title",
titlefont=dict(
color="#1f77b4"
),
tickfont=dict(
color="#1f77b4"
)
),
yaxis2=dict(
title="yaxis2 title",
titlefont=dict(
color="#ff7f0e"
),
tickfont=dict(
color="#ff7f0e"
),
anchor="free",
overlaying="y",
side="left",
position=0.15
),
yaxis3=dict(
title="yaxis3 title",
titlefont=dict(
color="#d62728"
),
tickfont=dict(
color="#d62728"
),
anchor="x",
overlaying="y",
side="right"
),
yaxis4=dict(
title="yaxis4 title",
titlefont=dict(
color="#9467bd"
),
tickfont=dict(
color="#9467bd"
),
anchor="free",
overlaying="y",
side="right",
position=0.85
)
)
# Update layout properties
fig.update_layout(
title_text="multiple y-axes example",
width=800,
)
fig.show()
我的 globals() 示例 # 不起作用
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6],
name="yaxis1 data"
))
fig.add_trace(go.Scatter(
x=[2, 3, 4],
y=[40, 50, 60],
name="yaxis2 data",
yaxis="y2"
))
fig.add_trace(go.Scatter(
x=[4, 5, 6],
y=[40000, 50000, 60000],
name="yaxis3 data",
yaxis="y3"
))
fig.add_trace(go.Scatter(
x=[5, 6, 7],
y=[400000, 500000, 600000],
name="yaxis4 data",
yaxis="y4"
))
# Create axis objects
fig.update_layout(
xaxis=dict(
domain=[0.3, 0.7]
),
yaxis=dict(
title="yaxis title",
titlefont=dict(
color="#1f77b4"
),
tickfont=dict(
color="#1f77b4"
)
),
for i in range(2,5):
globals()['yaxis' + str(i)] = dict(
title="yaxis" + str(i) + " title",
overlaying= overlay[i],
side=side[i],
position= position[i]
),
# Update layout properties
fig.update_layout(
title_text="multiple y-axes example",
width=800,
)
fig.show()
我想到的另一种方法是创建一个字典数组,用于绘图中的形状。我很好奇 plotly 是否有类似 y_axes 的东西
y = [dict(
title="yaxis" + str(i) + " title",
anchor= anchor[i],
overlaying= overlay[i],
side=side[i],
position= position[i]
) for i in range (2,5)]
y_axes = y
【问题讨论】: