matplotlib 变换不适用于axvspan(或axhspan)

anauzrmj  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(133)

我正在努力创建matplotlib axvspan(或axhspan)来处理变换后的坐标,但我不能。特别是,我想将yminymax定义为在transData坐标中工作,而不是在transAxes坐标中工作下面是我的测试代码(我的目标是在y=0y=1处的水平线之间绘制红色和蓝色背景):

import matplotlib.transforms as transforms
fig, ax = plt.subplots()
ax.set_ylim([-1, 2])
ax.set_xlim([0, 15])
ax.axhline(y=0)
ax.axhline(y=1)
# tried different ways to do this.
trans = transforms.blended_transform_factory(ax.transData, ax.transData)
ax.axvspan(8, 10, ymin=0, ymax=1, transform=trans, alpha=0.1, color='blue')
ax.axvspan(10, 12, ymin=0.1, ymax=0.8, transform=(ax.transData, ax.transData), alpha=0.5, color='red')
plt.show()

输出如下所示:

注意:我知道如何使用patches.rectangle来实现,但是我希望使用axvspan来实现(或者理解为什么不能)

m4pnthwp

m4pnthwp1#

我还使用反转的 y 轴测试了此方法,它在两种情况下都有效

def limits(a, b, ax):
    if a>b : a, b = b, a
    ymin, ymax = ax.get_ylim()
    dy = ymax-ymin
    return ((y-ymin)/dy for y in (a, b))

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_ylim([-1, 2]) # or ax.set_ylim([2, -1])
ax.set_xlim([0, 15])
ax.axhline(y=0)
ax.axhline(y=1)
ax.axvspan(8, 10, *limits(0, 1, ax))
plt.show()

相关问题