I am trying to make an interactive plot in plotly, such that I can choose from a selection of data streams in each subplot. In practise I have 27 potential plots, and want to let my user select which ones to show on 4 sub plots. My attempt is below:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime
df = pd.DataFrame({'time': [datetime(2020, 8, 1, 8+j, 5*k, 0) for j in range(3) for k in range(12)],
'A': np.random.randint(23, 51, 36),
'B': np.random.randint(30, 65, 36),
'C': np.random.randint(27, 63, 36),
'D': np.random.randint(40, 78, 36)})
df2 = pd.DataFrame({'time': [datetime(2020, 8, 1, 8+j, 5*k, 0) for j in range(3) for k in range(12)],
'E': np.random.randint(2, 5, 36),
'F': np.random.randint(3, 5, 36),
'G': np.random.randint(2, 6, 36),
'H': np.random.randint(4, 8, 36)})
#fig = go.Figure(go.Scatter(x=df['time'], y=df['A'], mode='lines', line_color='RoyalBlue'))
fig = plotly.subplots.make_subplots(rows=2, cols=1, shared_xaxes=True, shared_yaxes=False, vertical_spacing=0.01)
trace1 = go.Scatter(
x=df['time'],
y=df['A'],
showlegend=False
)
trace2 = go.Scatter(
x=df['time'],
y=df['B'],
showlegend=False
)
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)
labels=['A','B']
trace4 = go.Scatter(
x=df2['time'],
y=df2['E'],
showlegend=False
)
trace3 = go.Scatter(
x=df2['time'],
y=df2['F'],
showlegend=False
)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 1)
buttons = []
for i, label in enumerate(labels):
visibility = [i==j for j in range(len(labels))]
button = dict(
label = label,
method = 'update',
args = [{'visible': visibility},
{'title': label}])
buttons.append(button)
updatemenus = list([
dict(active=-1,
x=-0.15,
buttons=buttons
)
])
fig['layout']['title'] = 'Title'
fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus
fig.update_xaxes(title_text='Time', row=2, col=1)
plotly.offline.plot(fig)
I have not managed to get the buttons to allow indepedent swtiching of the subplot sources. ie. I would like to let the user select whether they would like to plot A or B on the upper subplot, and E or F on the lower subplot.
As an extension - I would also like to be able to rename the y axis when the buttons switch, and potentially have the option of showing multiple subplots, e.g having and 'A and B' option. Any advice on these if easy extensions is very much apprecaited.
Thanks for any help. A.