0

i use jupyterlab together with matplotlib widgets. I have ipywidgets installed. My goal is to choose which y-axis data is displayed in the bottom of the figure. When i use the interactive tool to see the coordinates i get only the data of the right y-axis displayed. Both would be really nice^^ My minimal code example:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib widgets
    
x=np.linspace(0,100)
y=x**2
y2=x**3

fig,ax=plt.subplots()
ax2=ax.twinx()
    
ax.plot(x,y)
ax2.plot(x,y2)

plt.show()

With this example you might ask why not to plot them to the same y-axis but thats why it is a minimal example. I would like to plot data of different units.

Jakob
  • 168
  • 1
  • 6

1 Answers1

2

To choose which y-axis is used, you can set the zorder property of the axes containing this y-axis to a higher value than that of the other axes (0 is the default):

ax.zorder = 1

However, that will cause this Axes to obscure the other Axes. To counteract this, use

ax.set_facecolor((0, 0, 0, 0))

to make the background color of this Axes transparent.

Alternatively, use the grab_mouse function of the figure canvas:

fig.canvas.grab_mouse(ax)

See here for the (minimal) documentation for grab_mouse.

The reason this works is this:

The coordinate line shown below the figure is obtained by an event callback which ultimately calls matplotlib.Axes.format_coord() on the axes instance returned by the inaxes property of the matplotlib events that are being generated by your mouse movement. This Axes is the one returned by FigureCanvasBase.inaxes() which uses the Axes zorder, and in case of ties, chooses the last Axes created.

However, you can tell the figure canvas that one Axes should receive all mouse events, in which case this Axes is also set as the inaxes property of generated events (see the code).

I have not found a clean way to make the display show data from both Axes. The only solution I have found would be to monkey-patch NavigationToolbar2._mouse_event_to_message (also here) to do what you want.

Daniel Sk
  • 420
  • 1
  • 4
  • 13