这里是一个用于编辑左右y轴的例子
在菜单的 arg 中,您需要添加一个带有索引的列表。 [0] 是添加的第一个跟踪 [1] 第二个等等。
ps 我不是“代码”专家,上周刚刚为 ChemE 论文“学习”了 python,所以我的代码可以工作,但它可能不是最好/最有效的
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
# Data
x = np.linspace(-np.pi, np.pi, 200)
y1 = np.sin(x) # f(x) = sin(x*pi)
y2 = np.cos(x) #f(x) = cos(x*pi)
y3 = np.tan(x) #f(x) = tan(x*pi)
d = {'x': x, 'y1': y1,'y2': y2,'y3': y3}
df = pd.DataFrame(data=d)
name = 'Test'
def Graph(df,name):
#Make fig
fig = make_subplots(specs=[[{"secondary_y": True}]])
#Add first trace
fig.add_trace(
go.Scatter(x=df['x'],
y=df['y1'],
),
secondary_y=False,)
#Add second trace
fig.add_trace(
go.Scatter(x=df['x'],
y=df['y2'],
),
secondary_y=True,)
# buttons for menu 1, contolling first trace
buttons1=[]
#Dynamic list based on df keys
for dfk in df.keys():
buttons1.append(dict(method='restyle',
label=dfk,
visible=True,
args=[{'y':[df[dfk].values]}, [0]], #The [0] 'locks' it to the first trace
)
)
# buttons for menu 2, contolling seccond trace
buttons2=[]
#Dynamic list based on df keys
for dfk in df.keys():
buttons2.append(dict(method='restyle',
label=dfk,
visible=True,
args=[{'y':[df[dfk].values]}, [1]], #The [1] 'locks' it to the second trace
)
)
#Delete x-axis from dropdown
del buttons1[0]
del buttons2[0]
#List for menus
updatemenu=[]
#add dict for buttons
your_menu1=dict()
updatemenu.append(your_menu1)
your_menu2=dict()
updatemenu.append(your_menu2)
#Fill dict
updatemenu[0]['buttons']=buttons1
updatemenu[0]['x']=0.15 #Some styling
updatemenu[0]['y']=1.12 #Some styling
updatemenu[1]['buttons']=buttons2
updatemenu[1]['x']=0.33 #Some styling
updatemenu[1]['y']=1.12 #Some styling
# add dropdown menus to the figure
fig.update_layout(showlegend=True, updatemenus=updatemenu)
# add notations to the dropdown menus
fig.update_layout(
annotations=[
dict(text="Left y-axis:", x=0, xref="paper", y=1.10, yref="paper",
align="left", showarrow=False),
dict(text="Right y-axis::", x=0.17, xref="paper", y=1.10,
yref="paper", showarrow=False)])
name = str(name)+'.html'
fig.write_html(name, auto_open=True)
Graph(df,name)