[Matplotlib-users] Share Y-axis on Subplot with Scaling

Chad Parker parker.charles at gmail.com
Tue Jul 7 21:00:00 EDT 2020


All-

I'm trying to do something similar to this example:
https://matplotlib.org/examples/axes_grid/parasite_simple2.html

However, instead of the parasite axes being overlaid with the primary one,
I'd like it to be a separate subplot that I can put different data on.
(Also, I'm trying to do this with a pair of y-axes, in case that's
relevant. It's not immediately obvious how to adjust the example to do this
with y instead of x.) Ultimately I want the second y-axis to set its range
to some multiple of the first. So, for example, if I set one axis to have a
y range of [0,64], I'd like the second subplot to automatically adjust its
range to [0,32]. (I'd also like to be able to link the x axes to adjust
together as normally done with the sharex keyword.)

My first thought was to modify the lines:

ax = SubplotHost(fig, 1, 1, 1)
...
ax_pm = ax_kms.twin(aux_trans)

to be:

ax = SubplotHost(fig, 2, 1, 1)
...
ax_pm = fig.add_subplot(212, transform=aux_trans)

but the result is a TypeError: unhashable type: 'Affine2D'.

Perhaps I'm getting transforms confused, and the transform keyword to
add_subplot is used to define its location on the figure instead of how
"twin" uses it to apparently scale the axes. The API just lists the keyword
as expecting a type "Transform", and mentions that it's passed along to the
Axes base class, which also just lists it as being of type "Transform".

(aside: is there documentation for the "SubplotHost" class? I don't see it
listed here:
https://matplotlib.org/3.1.1/api/_as_gen/mpl_toolkits.axes_grid1.parasite_axes.html
I went looking for the documentation of the "twin" function to see if I
could understand how it used the transform, but was unable to find it in
about 5 minutes of looking.)

To make it a little clearer what I'm after, here's some base code to set up
an example:

import matplotlib.pyplot as plt

xdata = [1, 2, 3, 4, 5, 6]
ydata = [2, 4, 8, 16, 32, 64]
ydata2 = [y/2 for y in ydata]

fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

ax1.plot(xdata, ydata)
ax2.plot(xdata, ydata2)

# <somehow link the two y axes>

ax1.set_ylim([0, 64])
# ax2.set_ylim([0, 32])  # happens automagically with the previous line

It would be super convenient if one could simply pass a transform as the
argument to sharey in the call to add_subplot...

Thanks for any help you might provide,
--Chad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-users/attachments/20200707/dcb0cc0f/attachment.html>


More information about the Matplotlib-users mailing list