@@ -308,6 +308,13 @@ def add_secondary_y(
308308 # Build mapping from primary y-axes to secondary y-axes
309309 y_mapping = _build_secondary_y_mapping (base_axes )
310310
311+ # Build x-y correspondence from base_axes (which x-axis pairs with which y-axis)
312+ x_for_y = {yaxis : xaxis for xaxis , yaxis in base_axes }
313+
314+ # Find the rightmost x-axis (highest number) to determine which secondary axis shows ticks
315+ rightmost_x = max (x_for_y .values (), key = lambda x : int (x [1 :]) if x != "x" else 1 )
316+ rightmost_primary_y = next (y for y , x in x_for_y .items () if x == rightmost_x )
317+
311318 # Create new figure with base's layout
312319 combined = go .Figure (layout = copy .deepcopy (base .layout ))
313320
@@ -322,24 +329,32 @@ def add_secondary_y(
322329 trace_copy .yaxis = y_mapping [original_yaxis ]
323330 combined .add_trace (trace_copy )
324331
332+ # Get the rightmost secondary y-axis name for linking
333+ rightmost_secondary_y = y_mapping [rightmost_primary_y ]
334+
325335 # Configure secondary y-axes
326336 for primary_yaxis , secondary_yaxis in y_mapping .items ():
327- # Get title - only set on first secondary axis or use provided title
337+ is_rightmost = primary_yaxis == rightmost_primary_y
338+
339+ # Get title - only set on rightmost secondary axis
328340 title = None
329- if secondary_y_title is not None :
330- # Only set title on the first secondary axis to avoid repetition
331- if primary_yaxis == "y" :
341+ if is_rightmost :
342+ if secondary_y_title is not None :
332343 title = secondary_y_title
333- elif primary_yaxis == "y" and secondary .layout .yaxis and secondary .layout .yaxis .title :
334- # Try to get from secondary's layout
335- title = secondary .layout .yaxis .title .text
344+ elif secondary .layout .yaxis and secondary .layout .yaxis .title :
345+ title = secondary .layout .yaxis .title .text
336346
337347 # Configure the secondary axis
348+ # Anchor to the corresponding x-axis so it appears on the right side of its subplot
338349 axis_config = {
339350 "title" : title ,
340351 "overlaying" : primary_yaxis ,
341352 "side" : "right" ,
342- "anchor" : "free" if primary_yaxis != "y" else None ,
353+ "anchor" : x_for_y [primary_yaxis ],
354+ # Only show ticks on the rightmost secondary axis
355+ "showticklabels" : is_rightmost ,
356+ # Link non-rightmost axes to the rightmost for consistent scaling
357+ "matches" : None if is_rightmost else rightmost_secondary_y ,
343358 }
344359 # Remove None values
345360 axis_config = {k : v for k , v in axis_config .items () if v is not None }
0 commit comments