python - 如何使用轴位置作为引用在 matplotlib 上跨多个轴绘制框

标签 python matplotlib

我想在多个轴上绘制一个框,使用一个轴坐标作为引用。我有的简单代码不会生成框是

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000 
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)
plt.show()

这会生成下图:

enter image description here

我想要的是下图,用ax2的x坐标来指定位置:

enter image description here

最佳答案

问题是矩形应该用于什么目的。如果它只是一个绑定(bind)到 ax2 但延伸到 ax1 的上边缘的矩形,则可以像这样创建一个矩形

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000 
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)

rect = plt.Rectangle((1,0), width=1, height=2+fig.subplotpars.wspace,
                     transform=ax2.get_xaxis_transform(), clip_on=False,
                     edgecolor="k", facecolor="none", linewidth=3)
ax2.add_patch(rect)

plt.show()

enter image description here

但这当然会保持原样,即使 ax1 的限制发生变化。这是想要的吗?

所以也许更有趣的解决方案是矩形遵循两个轴的坐标。以下内容仅在 matplotlib 3.1 中有效,截至今天,该版本仅作为预发行版本提供
(pip install --pre --upgrade matplotlib)

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=False, sharey=False, figsize=(15,9))

x = 2 * np.pi * np.arange(1000) / 1000 
y1 = np.sin(x)
y2 = np.cos(x)

ax1.plot(x,y1)
ax2.plot(x,y2)

def rectspan(x1, x2, ax1, ax2, **kwargs):
    line1, = ax1.plot([x1, x1, x2, x2],[0,1,1,0], 
                      transform=ax1.get_xaxis_transform(), **kwargs)
    line2, = ax2.plot([x1, x1, x2, x2],[1,0,0,1], 
                      transform=ax2.get_xaxis_transform(), **kwargs)
    for x in (x1, x2):
        p = ConnectionPatch((x,1), (x,0), 
                            coordsA=ax2.get_xaxis_transform(),
                            coordsB=ax1.get_xaxis_transform(), **kwargs)
        ax1.add_artist(p)

rectspan(1, 2, ax1, ax2, color="k", linewidth=3)
plt.show()

enter image description here

关于python - 如何使用轴位置作为引用在 matplotlib 上跨多个轴绘制框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814725/

相关文章:

python pandas dataframe resample.last 如何确保数据来自同一行

python - OpenERP : How to display fields of two objects within the same view?

python - 如何使用 secondary_y 调整 pandas 图的刻度和标签大小

python - 使用 pandas.cut() 并将其设置为数据帧的索引

python - 搜索估计器参数返回的结果不在网格中?

javascript - 如何将 python 与 javascript 结合使用?

Python 电子邮件标题奇怪的行为

python - 将两个高斯组合成另一个高斯

python - 使用 seaborn/matplotlib boxplot 时的刻度频率

python - 在干图中隐藏基线