【问题标题】:Connecting a point in an axis and another point in another axis by an arrow in matplotlib在matplotlib中用箭头连接轴上的一个点和另一个轴上的另一个点
【发布时间】:2012-05-07 20:03:34
【问题描述】:

使用 matplotlib,我正在制作一个包含两个 Axes 对象(即两组 xy 轴)的图形。我想通过箭头或线连接两个点——一个从一个轴上选取,另一个从另一个轴上选取。

我尝试通过使用 annotate() 函数和 ConnectionPatch 对象来做到这一点,但在这两种方式中,箭头的一部分都被轴的“框架”隐藏了。请参见附图,其中我尝试通过 ConnectionPatch 对象连接两个轴的原点。

我还附上了用于生成图形的脚本。

有没有办法让箭头“向前”(或将轴框架推到后面)?

#!/usr/bin/python
# 
# This script was written by Norio TAKEMOTO 2012-5-7


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

# creating a figure and axes.
fig=plt.figure(figsize=(10,5))

ax1=plt.axes([0.05,0.15,0.40,0.80])

plt.xticks([0])
plt.yticks([0])
plt.xlim((-1.23, 1.23))
plt.ylim((-2.34, 2.34))


ax2=plt.axes([0.60,0.15, 0.30, 0.30])

plt.xticks([0])
plt.yticks([0])
plt.xlim((-3.45, 3.45))
plt.ylim((-4.56, 4.56))


# trying to connect the point (0,0) in ax1 and the point (0,0) in ax2
# by an arrow, but some part is hidden. I can't find a solution. Let's
# ask stackoverflow.

#xy_A_ax1=(0,0)
#xy_B_ax2=(0,0)
#
#inv1 = ax1.transData.inverted()
#xy_B_display = ax2.transData.transform(xy_B_ax2)
#xy_B_ax1     = inv1.transform(xy_B_display)
#ax1.annotate('Wundaba', xy=(0, 0), xytext=xy_B_ax1,
#             xycoords='data',textcoords='data', 
#             arrowprops=dict(arrowstyle='->'))


con = ConnectionPatch(xyA=(0, 0), xyB=(0, 0), 
                      coordsA='data', coordsB='data', 
                      axesA=ax1, axesB=ax2,
                      arrowstyle='->', clip_on=False)
ax1.add_artist(con)

plt.savefig('fig1.eps')
plt.savefig('fig1.png')

【问题讨论】:

    标签: python matplotlib plot annotate


    【解决方案1】:

    一种简单的方法是将透明参数设置为savefig(),即plt.savefig('fig1.png', transparent=1)

    或者您可以只在第二张图上使用透明度:

    ax2.patch.set_facecolor('None')

    如第 21 行。

    【讨论】:

    • 感谢您的回答。两者都为我工作。但是,我仍然想知道一种控制箭头和轴框架的“zorder”的方法。如果我找到这样的方法,我稍后会在这里报告。
    【解决方案2】:

    这可以通过setting坐标轴上的z顺序来解决:

    import matplotlib.patches
    import matplotlib.pyplot as plt  # Vanilla matplotlib==2.2.2
    
    figure, (ax1, ax2) = plt.subplots(1, 2)
    ax1.set_zorder(1)
    ax2.set_zorder(0)
    
    patch = matplotlib.patches.ConnectionPatch(
        xyA=(0.0, 0.0),
        xyB=(0.0, 0.0),
        coordsA="data",
        coordsB="data",
        axesA=ax1,
        axesB=ax2,
        arrowstyle="->",
        clip_on=False,
    )
    ax1.add_artist(patch)
    
    for ax in (ax1, ax2):
        ax.axis("scaled")
    ax1.set_xlim(-0.25, 0.75)
    ax1.set_ylim(-0.5, 0.5)
    ax2.set_xlim(0.0, 1.0)
    ax2.set_ylim(0.0, 1.0)
    figure.savefig("example1.png")
    

    【讨论】:

    • 酷。谢谢你。您让我意识到我只需要设置 Axes 对象的 zorder,因为 ConnectionPatch 对象已添加到 Axes 对象之一。
    猜你喜欢
    • 2013-12-31
    • 2018-07-06
    • 2016-09-26
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多