vil*_*laa 9 python graph matplotlib
我想创建一组轴,以在父组轴的特定位置形成插入.因此,不宜只使用参数loc=1,2,3
中inset_axes
,如下所示:
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
Run Code Online (Sandbox Code Playgroud)
但是,我想要接近这一点.这里和这里的答案似乎是比我复杂得多的问题的答案.
所以,问题是我可以在上面的代码中替换一个参数,它允许插入轴在父轴中的自定义位置吗?我试图使用bbox_to_anchor
但不理解文档中的规范或行为.具体来说,我尝试过:
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
bbox_to_anchor=(0.4,0.1))
Run Code Online (Sandbox Code Playgroud)
尝试使插图的左侧和底部的锚点分别位于x轴和y轴的40%和10%处.或者,我试图把它放在绝对坐标中:
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
bbox_to_anchor=(-4,-100))
Run Code Online (Sandbox Code Playgroud)
这些都没有正常工作,并给了我一个我无法解释的警告.
更一般地说,它似乎loc
是属于许多函数的一个非常标准的参数matplotlib
,因此,是否可以在任何地方使用这个问题的一般解决方案?看起来就是这样bbox_to_anchor
但又一次,我无法弄清楚如何正确使用它.
你采取的方法原则上是正确的.但是,就像放置图例时一样bbox_to_anchor
,该位置被确定为bbox_to_anchor
和之间的相互作用loc
.上述链接答案中的大多数解释也适用于此.
默认loc
为inset_axes
IS loc=1
("右上").这意味着如果您指定bbox_to_anchor=(0.4,0.1)
,那将是右上角的坐标,而不是左下角的坐标.
因此,您需要指定loc=3
将插图的左下角定位在(0.4,0.1)
.
但是,如果不以相对单位("30%"
)指定宽度和高度,则将边界指定为2元组才有意义.或者换句话说,为了使用相对单位,你需要使用4元组表示法bbox_to_anchor
.
如果指定了bbox_to_anchor
in轴单位,则需要bbox_transform
再次使用该参数,就像这里解释的图例一样,并将其设置为ax.transAxes
.
plt.figure(figsize=(6,3))
ax = plt.subplot(221)
ax.set_title("100%, (0.5,1-0.3,.3,.3)")
ax.plot(xdata, ydata)
axins = inset_axes(ax, width="100%", height="100%", loc='upper left',
bbox_to_anchor=(0.5,1-0.3,.3,.3), bbox_transform=ax.transAxes)
ax = plt.subplot(222)
ax.set_title("30%, (0.5,0,1,1)")
ax.plot(xdata, ydata)
axins = inset_axes(ax, width="30%", height="30%", loc='upper left',
bbox_to_anchor=(0.5,0,1,1), bbox_transform=ax.transAxes)
Run Code Online (Sandbox Code Playgroud)
在matplotlib页面上找到一个完整的示例:Inset Locator Demo
另一个选择是使用InsetPosition
而不是inset_axes
和给现有轴一个新位置.InsetPosition
将标准化轴坐标中轴的左下角的x和y坐标以及宽度和高度作为输入.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
fig, ax= plt.subplots()
iax = plt.axes([0, 0, 1, 1])
ip = InsetPosition(ax, [0.4, 0.1, 0.3, 0.7]) #posx, posy, width, height
iax.set_axes_locator(ip)
iax.plot([1,2,4])
plt.show()
Run Code Online (Sandbox Code Playgroud)
最后应该提一下,从matplotlib 3.0开始,你可以使用matplotlib.axes.Axes.inset_axes
import matplotlib.pyplot as plt
plt.figure(figsize=(6,3))
ax = plt.subplot(221)
ax.set_title("ax.inset_axes, (0.5,1-0.3,.3,.3)")
ax.plot([0,4], [0,10])
axins = ax.inset_axes((0.5,1-0.3,.3,.3))
plt.show()
Run Code Online (Sandbox Code Playgroud)
结果大致相同,只是mpl_toolkits.axes_grid1.inset_locator.inset_axes
允许围绕轴填充(并默认应用它),而Axes.inset_axes
没有这种填充.
归档时间: |
|
查看次数: |
4833 次 |
最近记录: |