3

I have two different datasets (x0,y0), (x1,y1). I need to create two plots and use a drop down menu to select between them.

I am using this code:

import plotly
import plotly.graph_objs as go
import random

x0 = [x for x in range(0,20)]
x1 = [x for x in range(5,100)]

y0 = [random.randint(0,20) for x in range(len(x0))]
y1 = [random.randint(0,50) for x in range(len(x1))]

trace1 = go.Scatter(x=x0,y=y0,line=dict(shape='vh'))
trace2 = go.Scatter(x=x1,y=y1,line=dict(shape='vh'))

data = [trace1,trace2]

updatemenus = list([
    dict(active=0,
         buttons=list([   
            dict(label = "4 Aug 1",
                 method = "update",
                 args= [data[0]]),
            dict(label = "4 Aug 2",
                 method = "update",
                 args= [data[1]])]))])


layout = dict(title="Dropdown",
              showlegend=True,
              xaxis=dict(title="Hours"),
              yaxis=dict(title="Number"),
              updatemenus=updatemenus)

fig=dict(data=data, layout=layout)

plotly.offline.plot(fig)

Using this code, it plots two datasets into one area, which I would not like to do. And when I select a proper chart on dropdown menu, it just fails to load proper chart.

0

1 Answer 1

5

The problem is that you're directly assigning traces to args. Instead, you should be using the visible property to control which traces in data are visible:

updatemenus = list([
    dict(active=0,
         showactive = True,
         buttons=list([   
            dict(label = "4 Aug 1",
                 method = "update",
                 args = [{"visible": [True, False]}]), # hide trace2
            dict(label = "4 Aug 2",
                 method = "update",
                 args = [{"visible": [False, True]}]) # hide trace1
            ]))])

If you only want to show the first trace when the page is loaded, you also need to explicitly set the visible attribute of the second trace to False:

trace1 = go.Scatter(x=x0,y=y0,line=dict(shape='vh'))
trace2 = go.Scatter(x=x1,y=y1,line=dict(shape='vh'), visible=False)
data = [trace1,trace2]

See the official Plotly example.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this works perfectly. Thank you. May I just ask what active = 0 stands for? I couldn't find that in documentation. Thanks.
active determines which entry in the drop-down is selected when you load the page. So right now active=0 means that the first entry 4 Aug 1 is selected in the drop-down. You can also set it to -1, so that no entry is selected. See plot.ly/python/reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.