When item in the legend is toggled off, the active datapoints will take up the freed space in the plot. However, if the y-axis range has been adjusted, the space remains empty. How to fix?
import plotly.graph_objects as go
import pandas as pd
import numpy as np
np.random.seed(42)
df = pd.DataFrame({
'red': np.random.randn(50),
'blue': np.random.randn(50) + 2,
'green': np.random.randn(50) + 1,
'orange':np.random.randn(50) + 3,
})
fig = go.Figure()
for i in df.columns:
fig.add_trace(go.Scatter(
x=df[i],
y=[i] * df[i].shape[0],
name=i,
mode='markers',
marker_color= 'blue' if 'blue' in i else 'green' if 'green' in i else 'red' if 'red' in i else 'orange',
legendgroup=i,
showlegend=True
))
fig.update_layout(legend_traceorder='reversed')
fig.show() # if one item in the legend is toggled off, all space will be redistributed to displayed data points
# after adjusting range, space will remain empty when toggled off some data
fig.update_layout(height=800) # to maximize the impact the issue
fig.update_yaxes(range=[-0.5, len(df.columns)-0.5])
fig.show()