【问题标题】:FancyArrowPatch not drawing labelFancyArrowPatch 不绘制标签
【发布时间】:2018-12-23 20:00:11
【问题描述】:

我无法让 FancyArrowPatch 显示传递给 label kwarg 的文本。我看不出我做错了什么。有什么想法吗?

设置:

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

fig = plt.figure()

X, Y = np.mgrid[-1:1:.1, -1:1:.1]
Z = X+Y

ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(313)
ax1.contourf(X, Y, Z)
ax2.contourf(X, Y, -Z)

箭头代码:

ax1tr = ax1.transData # Axis 0 -> Display
ax2tr = ax2.transData # Axis 1 -> Display
figtr = fig.transFigure.inverted() # Display -> Figure
ptB = figtr.transform(ax1tr.transform((0., 0.)))
ptE = figtr.transform(ax2tr.transform((0., 0.)))
arrow = patches.FancyArrowPatch(
    ptB, ptE, transform=fig.transFigure,  # Place arrow in figure coord system
    connectionstyle="arc3,rad=0", arrowstyle='simple',
    mutation_scale = 15., label='some arrow'
)
fig.patches.append(arrow)

fig.show()

我希望 some arrow 被绘制为箭头的标签。但事实并非如此。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    原则上它应该在您的代码中添加plt.legend() 行后工作。但是,有一个解决方法如下,您可以显式传递arrow 补丁和标签文本。

    arrow = patches.FancyArrowPatch(
        ptB, ptE, transform=fig.transFigure,  # Place arrow in figure coord system
        connectionstyle="arc3,rad=0", arrowstyle='simple',
        mutation_scale = 15., label='some arrow'
    )
    fig.patches.append(arrow)
    
    plt.legend([arrow], fontsize=16)
    

    另一种选择是

    plt.legend(handles=[arrow], fontsize=16)
    

    基于 cmets,正如我所说,label 的目的不是将文本放在箭头补丁旁边。使用plt.text 可以轻松实现您想要的。但是,如果您不想使用它,可以使用以下解决方法使当前代码按需要工作

    leg = plt.legend(handles = [arrow], fontsize=16, frameon=False, loc=(0.45, 0.5))
    
    for item in leg.legendHandles:
        item.set_visible(False)
    

    【讨论】:

    • 啊,我明白了,谢谢。不幸的是,这甚至不是我想要的(箭头旁边的标签)。
    • @lotolmencre:那你想要什么?也许你应该让你的问题更清楚。您的问题是“我无法让 FancyArrowPatch 显示传递给标签 kwarg 的测试”,其中“测试”我确定您的意思是“文本”
    • 我想要箭头旁边的标签。像 graphviz 标签或 tikz 标签。
    • 我不认为这是关键字“标签”的作用。对于您想要的,您可以简单地将plt.text 与垂直对齐的文本一起使用
    • 所以没有办法将文本附加到箭头上?这似乎很笨拙,将它添加到图形/轴/到plt
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 2016-10-05
    • 2014-03-22
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多