3

关于在 matplotlib 中的子图中嵌入小图的帖子的帖子,我正在研究这个解决方案,但由于某种原因,转换被忽略了!

我错了吗?还是有错误?

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()
4

1 回答 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()

产量

在此处输入图像描述

于 2013-07-04T21:21:19.300 回答