fig.add_subplot() *transform* doesn't work?
Asked Answered
Y

1

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()
Yenta answered 4/7, 2013 at 21:13 Comment(0)
T
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

Tisatisane answered 4/7, 2013 at 21:21 Comment(4)
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 #17459080Yenta
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.Yenta
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.Tisatisane
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. #17459080Yenta

© 2022 - 2024 — McMap. All rights reserved.