Hello, i am having a problem with my code. I managed to create a code that lets me slide up and down the lines over the y axis. however everytime that i choose a new variable the offset is reseted. how can i prevent this?
The code in question
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# Example DataFrame
data = {
'x': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'y1': [0, 1, 2, 5, 2, 6, 7, 2, 3],
'y2': [50, 51, 52, 25, 52, 56, 57, 52, 53],
'y3': [26, 65, 52, 25, 52, 56, 57, 52, 53],
'y4': [50, 54, 52, 22, 52, 56, 57, 55, 53]
}
df = pd.DataFrame(data)
# Initialize offsets
offsets = {col: 0 for col in df.columns[1:]}
current_col = df.columns[1] # Start with the first column
# Create the figure
fig = go.Figure()
# Add traces for each column
for col in df.columns[1:]:
fig.add_trace(go.Scatter(x=df['x'], y=df[col] + offsets[col], mode='lines', name=col))
# Function to generate slider steps
def create_slider_steps(selected_col):
steps = []
for step in np.arange(-10, 11, 1):
step_dict = {
'label': str(step),
'method': 'update',
'args': [
{'y': [df[c] + (step if c == selected_col else offsets[c]) for c in df.columns[1:]]},
{
'sliders': [{
'currentvalue': {'prefix': f"Offset for {selected_col}: {step}"},
'pad': {'t': 50}
}]
}
]
}
# When a step is selected, update the corresponding offset
step_dict['args'].append({'args2': offsets.update({selected_col: step})})
steps.append(step_dict)
return steps
# Function to create dropdown buttons
def create_dropdown_buttons():
dropdown_buttons = []
for col in df.columns[1:]:
dropdown_buttons.append({
'label': col,
'method': 'update',
'args': [
{'y': [df[c] + offsets[c] for c in df.columns[1:]]},
{
'sliders': [{
'steps': create_slider_steps(col),
'currentvalue': {'prefix': f"Offset for {col}: {offsets[col]}"},
'pad': {'t': 50},
}]
}
]
})
return dropdown_buttons
# Update layout with dropdown menu and slider
fig.update_layout(
title='Interactive Plot with Adjustable Offsets',
yaxis=dict(title='Values'),
updatemenus=[
{
'buttons': create_dropdown_buttons(),
'direction': 'down',
'showactive': True
}
],
sliders=[{
'steps': create_slider_steps(current_col),
'currentvalue': {'prefix': f"Offset for {current_col}: {offsets[current_col]}"},
'pad': {'t': 50}
}]
)
# Show the plot
fig.show()