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()
Community
  • 1
  • 1
Pablo
  • 2,443
  • 1
  • 20
  • 32

1 Answers1

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

j08lue
  • 1,647
  • 2
  • 21
  • 37
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 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 http://stackoverflow.com/questions/17458580/embedding-small-plots-inside-subplots-in-matplotlib – Pablo Jul 04 '13 at 21:24
  • 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. – Pablo Jul 04 '13 at 22:35
  • 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. – unutbu Jul 05 '13 at 00:22
  • 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. http://stackoverflow.com/questions/17458580/embedding-small-plots-inside-subplots-in-matplotlib/17479417#17479417 – Pablo Jul 05 '13 at 00:46