如何在 matplotlib 中绘制一个矩形,宽度始终为 xaxis 的 10%,高度始终为 1(yaxis 的单位),即使在 zoomed/moved 时也坚持到角落?
How to plot a rectangle in matplotlib, width always 10% of xaxis, height always 1 (unit of yaxis), sticking to corner even when zoomed/moved?
我查看了 matplotlib.transforms 模块,但还没有弄清楚如何同时实现以下所有目标。
- 用列表 x 和 y 中的 x 和 y 坐标绘制一条曲线。
- 绘制一个贴在左下角的矩形 (matplotlib.patches.Rectangle)
- 矩形的宽度是水平轴的 10% (xmax-xmin)。
- 高度为1,表示一个单位高度的矩形
- 当 plot 为 moved/zoomed.
时,矩形贴在左下角
- 缩放后矩形的宽度保持为水平轴 0.1*(xmax-xmin) 的 10%
- 矩形的高度在缩放时与 y 轴一致变化。
貌似水平方向,scale和position都在axes.transAxes,好办。但是,在垂直方向上,我需要在 axes.transData 中缩放,但在 axes.transAxes 中定位。如果我放弃第 5 项,我可以使用 transforms.blended_transform_factory(),使水平方向为 axes.transAxes,垂直方向为 axes.transData,在这种情况下,如果我缩放,矩形的高度正确更改,但它可能会在垂直方向上部分或完全超出视线范围。
有谁知道这是否可行而无需对 matplotlib 进行过多的修改?
您可以子类化 AnchoredOffsetbox
让美术师“固定”在坐标轴的特定位置。参见 Anchored Artists demo
演示代码:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import OffsetBox, AnchoredOffsetbox, AuxTransformBox
class AnchoredRectangle(AnchoredOffsetbox):
def __init__(self, transform, width, height, loc, **rect_kwds):
self._box = AuxTransformBox(transform)
self.rectangle = Rectangle((0, 0), width, height, **rect_kwds)
self._box.add_artist(self.rectangle)
super().__init__(loc, pad=0, borderpad=0,
child=self._box, frameon=False)
fig, ax = plt.subplots()
r = AnchoredRectangle(ax.get_yaxis_transform(), width=0.1, height=1,
loc='lower left', color='green', alpha=0.5)
ax.add_artist(r)
ax.set_xlim(0,1)
ax.set_ylim(0,2)
plt.show()
我查看了 matplotlib.transforms 模块,但还没有弄清楚如何同时实现以下所有目标。
- 用列表 x 和 y 中的 x 和 y 坐标绘制一条曲线。
- 绘制一个贴在左下角的矩形 (matplotlib.patches.Rectangle)
- 矩形的宽度是水平轴的 10% (xmax-xmin)。
- 高度为1,表示一个单位高度的矩形
- 当 plot 为 moved/zoomed. 时,矩形贴在左下角
- 缩放后矩形的宽度保持为水平轴 0.1*(xmax-xmin) 的 10%
- 矩形的高度在缩放时与 y 轴一致变化。
貌似水平方向,scale和position都在axes.transAxes,好办。但是,在垂直方向上,我需要在 axes.transData 中缩放,但在 axes.transAxes 中定位。如果我放弃第 5 项,我可以使用 transforms.blended_transform_factory(),使水平方向为 axes.transAxes,垂直方向为 axes.transData,在这种情况下,如果我缩放,矩形的高度正确更改,但它可能会在垂直方向上部分或完全超出视线范围。
有谁知道这是否可行而无需对 matplotlib 进行过多的修改?
您可以子类化 AnchoredOffsetbox
让美术师“固定”在坐标轴的特定位置。参见 Anchored Artists demo
演示代码:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import OffsetBox, AnchoredOffsetbox, AuxTransformBox
class AnchoredRectangle(AnchoredOffsetbox):
def __init__(self, transform, width, height, loc, **rect_kwds):
self._box = AuxTransformBox(transform)
self.rectangle = Rectangle((0, 0), width, height, **rect_kwds)
self._box.add_artist(self.rectangle)
super().__init__(loc, pad=0, borderpad=0,
child=self._box, frameon=False)
fig, ax = plt.subplots()
r = AnchoredRectangle(ax.get_yaxis_transform(), width=0.1, height=1,
loc='lower left', color='green', alpha=0.5)
ax.add_artist(r)
ax.set_xlim(0,1)
ax.set_ylim(0,2)
plt.show()