首页 > 解决方案 > Plotly:有没有办法只更改 add_trace 元素之一而不是全部?

问题描述

在 python3 中,我正在尝试编辑特定的 add_trace() 图。对于上下文,我创建了一个带有下拉菜单的 Plotly 图来更改/更新绘图本身。

示例代码

我正在绘制一个采用 x、y、z 的 3D 散点图。但后来我在同一个图 go.Surface 中添加了一个平面图,它是数据的平面估计。

这样做的问题是,当我更改一个属性时,比如 X 轴的“x”,它也会在 go.Surface 中更改“x”属性,这应该只是数据的估计而不是数据本身.

有没有办法分离特定的 add_trace() 属性,以便更新数据参数不会影响 go.Surface 参数?

标签: pythonplotly

解决方案


这是一个示例,用于在菜单的 arg 中编辑左右 y 轴,您需要添加带有索引的列表。[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)

推荐阅读