3

Regarding to the post Embedding small plots inside subplots in matplotlib, I'm working on this solution, but for some reason, transform is ignored!

I'm in a mistake? Or there is a bug?

import matplotlib.pyplot as plt
import numpy as np

axes = []
x = np.linspace(-np.pi,np.pi)
fig = plt.figure(figsize=(10,10))
subpos = (0,0.6)

for i in range(4):
   axes.append(fig.add_subplot(2,2,i))

for axis in axes:
    axis.set_xlim(-np.pi,np.pi)
    axis.set_ylim(-1,3)
    axis.plot(x,np.sin(x))
    fig.add_axes([0.5,0.5,0.1,0.1],transform=axis.transAxes)

plt.show()

1 Answer 1

5
import matplotlib.pyplot as plt
import numpy as np

def axis_to_fig(axis):
    fig = axis.figure
    def transform(coord):
        return fig.transFigure.inverted().transform(
            axis.transAxes.transform(coord))
    return transform

def add_sub_axes(axis, rect):
    fig = axis.figure
    left, bottom, width, height = rect
    trans = axis_to_fig(axis)
    figleft, figbottom = trans((left, bottom))
    figwidth, figheight = trans([width,height]) - trans([0,0])
    return fig.add_axes([figleft, figbottom, figwidth, figheight])

x = np.linspace(-np.pi,np.pi)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,10))

for axis in axes.ravel():
    axis.set_xlim(-np.pi, np.pi)
    axis.set_ylim(-1, 3)
    axis.plot(x, np.sin(x))
    subaxis = add_sub_axes(axis, [0.2, 0.6, 0.3, 0.3])
    subaxis.plot(x, np.cos(x))

plt.show()

yields

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

The main question is to use some method for emulate plt.axes() in subplots. The idea is to do small subplots inside each subplot of a grid. Look at stackoverflow.com/questions/17458580/…
Ok, but it is not the answer to my question... I know how to do it with a similar method as you, but I don't understand why transform karg is supported by fig.add_axes() and doesn't work.
The transform kwarg -- at most -- converts points from one coordinate system to another. The height and width are ratios, not points, so there is no way the transform kwarg could be used to single-handedly convert the [left, bottom, width, height] list from being with respect to the axis to being the approprate list with respect to the figure.
Yes, but converts ratios is trivial in a box. So, I don't understand why transform is a karg of add_axes. Anycase, it was useful. Thanks. I have another post to contribute with this problem, very similar to your solution. stackoverflow.com/questions/17458580/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.