Search code examples
pythonmatplotlibplotprojectionsubplot

Update the x-axis of a matplotlib subplot according to the y-axis of a different subplot


I would like to plot an orthogonal projection like this one:

orthogonal projection

using matplotlib, possibly including the 3D subplot. All the subplots should share common axes.

fig = plt.figure()
ax = fig.add_subplot(221, title="XZ")
bx = fig.add_subplot(222, title="YZ", sharey=ax)
cx = fig.add_subplot(223, title="XY", sharex=ax, sharey=[something like bx.Xaxis])
dx = fig.add_subplot(224, title="XYZ", projection="3d", sharex=ax, sharey=bx, sharez=[something like bx.Yaxis]

I can't figure out how to "link" the x-axis of one plot with the y-axis of another. Is there a way to accomplish this?


Solution

  • I solved1 the problem by exploiting event handlers. Listening for "*lim_changed" events and then properly get_*lim and set*_lim to synchronise the limits does the trick. Note you also have to reverse the x-axis in the upper right plot YZ.

    Here is a sample function to sync the x-axis with the y-axis:

    def sync_x_with_y(self, axis):
        # check whether the axes orientation is not coherent
        if (axis.get_ylim()[0] > axis.get_ylim()[1]) != (self.get_xlim()[0] > self.get_xlim()[1]):
            self.set_xlim(axis.get_ylim()[::-1], emit=False)
        else:
            self.set_xlim(axis.get_ylim(), emit=False)
    

    I implemented a simple class Orthogonal Projection that make quite easy to make such kind of plots.

    1 Starting from a hint that Benjamin Root gave me on matplotlib mailing list almost a year ago...sorry for not having posted the solution before