gpt4 book ai didi

python - 将 mark_inset 与不同的范围图一起使用

转载 作者:行者123 更新时间:2023-12-01 01:44:44 24 4
gpt4 key购买 nike

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

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")

结果是一个空插图:

enter image description here

但这很明显,因为我将 xy 的限制设置为 x**3 不通过的范围。例如,我想看到的是插图中 01x**3 图,而 mark_inset仍然会“缩放”到上面框出的区域,该区域具有不同的范围。

我该怎么做?

最佳答案

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

使用矩形

相反,您可以将某个矩形放置在您想要的任何位置,并使用 ConnectionPatches 在插图和矩形之间绘制一些线条。

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

在这两种情况下,结果图看起来都是这样的

enter image description here

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

关于python - 将 mark_inset 与不同的范围图一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51504323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com