filtertips
filtertips

Reputation: 903

Plot two different datasets into plotly using drop down menu

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.

Upvotes: 3

Views: 3085

Answers (1)

glhr
glhr

Reputation: 4547

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.

Upvotes: 5

Related Questions