Hide axis tick-labels when data deactivated in Plotly legend

752 views Asked by At

In order to have a box plot on top of markers, I used a second axis. However, when toggling off things in the legend, the tick-labels stay in the plot. This makes the toggling off almost pointless when I have dozens of variables/box plots since it leaves a lot of space between the active data. Ideas how to fix?

import plotly.graph_objects as go
import numpy as np

np.random.seed(42)
y0 = np.random.randn(50)
y1 = np.random.randn(50) + 1
y2 = np.random.randn(50) + 2 # shift mean
x0 = 'Sample A'
x1 = 'Sample B'
x2 = 'Sample C'

fig = go.Figure()
fig.add_trace(go.Scatter(
    y=[x0]*len(y0),
    x=y0,
    mode='markers',
    name='Sample A',
    legendgroup='A',
    showlegend=False
))
fig.add_trace(go.Scatter(
    y=[x1]*len(y1),
    x=y1,
    mode='markers',
    name='Sample B',
    legendgroup='B',
    showlegend=False
))
fig.add_trace(go.Scatter(
    y=[x2]*len(y2),
    x=y2,
    mode='markers',
    name='Sample C',
    legendgroup='C',
    showlegend=False
))

fig.add_trace(go.Box(
    x=y0, 
    name='Sample A',
    marker_color = 'indianred',
    boxpoints=False,
    legendgroup='A',
    yaxis='y2'
))
fig.add_trace(go.Box(
    x=y1, 
    name='Sample B',
    marker_color = 'lightseagreen',
    boxpoints=False,
    legendgroup='B',
    yaxis='y2'
))
fig.add_trace(go.Box(
    x=y2, 
    name='Sample C',
    marker_color = 'orange',
    boxpoints=False,
    legendgroup='C',
    yaxis='y2'
))

fig.update_layout(
    yaxis2=dict(
        matches='y',
        layer="above traces",
        overlaying="y",    
        showticklabels=False
))

fig.show()

enter image description here

1

There are 1 answers

1
r-beginners On

I don't know why it looks like this, but if you don't set matches= in the layout, the legend toggle on/off does what it's intended to do. If I try to display the second axis, only sample B is in the same position.

fig.update_layout(
    yaxis2=dict(
#         matches='y',
        layer="above traces",
        overlaying="y",    
        showticklabels=True
))

fig.show()

enter image description here