关于帖子Embedding small plots inside subplots in 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()
答案 0 :(得分:4)
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()
产量