简体   繁体   中英

Plotly Dropdown not updating graphs correctly

I am working on creating dropdown menu for my data here is my data

data = {'Time': [2,4,5,6,7], 'Voltage': [20.3, 17.2,15.3,9.4,2], "Current":[2, 5,7,8,9]}  
df = pd.DataFrame(data)

this is the code for plotting dropdowns

plot = px.Figure(data=[go.Scatter( 

    name='Voltage', 

    x=df["Time"], 

    y=df["Voltage"]
), 

    go.Scatter( 

    name='Data 2', 

    x=df["Time"], 

    y=df["Current"] 
) 
]) 

plot.update_layout( 

    updatemenus=[ 

        dict( 
            buttons=list([ 

                dict(label="Voltage", 

                     method="update", 

                     args=[{"visible": [True, False]}, 

                           {"title": "Voltage", 

                            }]), 

                dict(label="Current", 

                     method="update", 

                     args=[{"visible": [False, True]}, 

                           {"title": "Data 2", 

                            }]), 

            ]), 

        ) 

    ]) 
plot.show() 

even though i am not selecting both plots to display it is showing both plots how to overcome this thanks and regards

You need to add visible = False to second scatter. So it should be:

go.Scatter( 

name='Data 2', 

x=df["Time"], 

y=df["Current"] ,

visible = False) 

Your code defines the two scatter plots as one graph, so if you rewrite it to set up two graphs, the buttons are not set up incorrectly and the graph can be changed by the drop down buttons.

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(name='Voltage', x=df["Time"], y=df["Voltage"], line_color='blue')) 
fig.add_trace(go.Scatter(name='Data 2', x=df["Time"],  y=df["Current"], line_color='red'))

fig.update_layout( 
    updatemenus=[ 
        dict( 
            buttons=list([ 
                dict(label="Voltage", 
                     method="update", 
                     args=[{"visible": [True, False]}, 
                           {"title": "Voltage", 
                            }]), 
                dict(label="Current", 
                     method="update", 
                     args=[{"visible": [False, True]}, 
                           {"title": "Data 2", 
                            }]), 
            ]), 

        ) 

    ]) 
fig.show()

在此处输入图像描述 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM