Python 使用带有不同范围图的mark_插图

Python 使用带有不同范围图的mark_插图,python,matplotlib,Python,Matplotlib,假设我要将绘图插入到地物,但插入绘图的轴范围与我标记插入的轴范围不同。例如: fig, ax = plt.subplots() axins = inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure) x = np.linspace(0, 3, 100) y = x**2 ax.plot(x, y) axins.plot(x, x**3) x1, x2, y1, y

假设我要将绘图插入到地物,但插入绘图的轴范围与我标记插入的轴范围不同。例如:

fig, ax = plt.subplots()
axins = inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)

x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)

x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
axins.set_xlim(x1, x2) # apply the x-limits
axins.set_ylim(y1, y2) # apply the y-limits

plt.xticks(visible=False)
plt.yticks(visible=False)

mark_inset(ax, axins, loc1=4, loc2=1)#, fc="none")#, ec="0.5")
结果是一个空的插入图:

但这是显而易见的,因为我将
x
y
的限制设置为
x**3
无法通过的范围。 我想看到的是,例如,插图中
0
1
x**3
绘图,而标记插图仍将“缩放”到上面框中的区域,该区域的范围不同


如何执行此操作?

在这种情况下,您不能直接使用
标记插入
,因为这正是此函数的作用:将标记与插入的轴限制同步

使用矩形 相反,您可以将某个矩形放置在您想要的位置,并使用
ConnectionPatch
es在插入和矩形之间绘制一些线

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il
import matplotlib.patches as mpatches

fig, ax = plt.subplots()

axins = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)

x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)

x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
rect = mpatches.Rectangle((x1,y1), width=x2-x1, height=y2-y1, facecolor="None", edgecolor="k", linewidth=0.8)
fig.canvas.draw()
p1 = mpatches.ConnectionPatch(xyA=(1,0), xyB=(x2,y1), coordsA="axes fraction", coordsB="data",  axesA=axins, axesB=ax)
p2 = mpatches.ConnectionPatch(xyA=(1,1), xyB=(x2,y2), coordsA="axes fraction", coordsB="data",  axesA=axins, axesB=ax)

ax.add_patch(rect)
ax.add_patch(p1)
ax.add_patch(p2)

plt.show()
使用虚拟轴 您也可以简单地添加一个附加插图,仅用于使用
mark_inset

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator as il

fig, ax = plt.subplots()
axins_dummy = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)
axins = il.inset_axes(ax, 1,1 , loc=2, bbox_to_anchor=(0.35,0.85),bbox_transform=ax.figure.transFigure)

x = np.linspace(0, 3, 100)
y = x**2
ax.plot(x, y)
axins.plot(x, x**3)

x1, x2, y1, y2 = 2.,3, 6, 8 # specify the limits
axins_dummy .set_xlim(x1, x2) # apply the x-limits
axins_dummy .set_ylim(y1, y2) # apply the y-limits

axins_dummy.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False )

il.mark_inset(ax,axins_dummy , loc1=4, loc2=1)#, fc="none")#, ec="0.5")

plt.show()
在这两种情况下,生成的绘图如下所示


也许值得注意的是,结果图当然是不正确的。任何读者都会认为插图显示了曲线的一部分,但事实并非如此。因此,请确保不要在出版物或报告中使用此类图表。

谢谢。关于您最后的评论,实际目的是关注数量的时间演变中的快照,然后在一个小数字上绘制相关的概要