【问题标题】:Dynamically add legend for arrows in matplotlib在 matplotlib 中为箭头动态添加图例
【发布时间】:2018-08-03 21:41:59
【问题描述】:
import matplotlib.pyplot as plt
def plot_arrow(arrow_type):
    if arrow_type == 'good_arrow':
        arrow_color = 'g'
    ar = plt.arrow(x, y, dx , dy, label=arrow_type, fc=arrow_color)
    plt.legend([ar,], [arrow_type,])

上述回调函数用于在绘图中绘制箭头。我需要为他们添加图例。这些箭头是动态绘制的。上面的代码只有一个图例。我尝试了this 之类的解决方案,但这些解决方案不适用于matplotlib.pyplot.arrow

编辑

问题:我有两个彩色箭头,但只有一个图例

绘图示例:

【问题讨论】:

  • 你能分享一些示例输出图像吗?
  • 我添加了一个链接。不知道为什么我不能嵌入它
  • 不要在这个函数中绘制图例。相反,返回艺术家并在调用此函数的代码块中创建图例。
  • 这个函数是一个回调。
  • 为箭头创建图例有问题吗(实际上显示的是箭头而不是矩形)?还是更新图例?

标签: python matplotlib


【解决方案1】:

在您的情况下,为什么不直接使用quiver()?见here

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

def rand(n):
    return 2.0*np.random.rand(n)-1.0

def plt_arrows(n, c, l, xpos, ypos):
    X, Y = rand(n), rand(n)
    U, V = 4.*rand(n), 4.*rand(n)
    Q = plt.quiver(X, Y, U, V, angles="xy", scale=30, label=l, color=c)
    qk = plt.quiverkey(Q, xpos, ypos, 2, label=l, labelpos='N', labelcolor=c)

plt_arrows(20, "g", "good", 1.05, 0.9)
plt_arrows(20, "r", "bad", 1.05, 0.8)

plt.show()

【讨论】:

  • 谢谢塞缪尔。我会有大约 100 个箭头。所以我想要一个颜色的图例,而不是每个箭头。而且我还试图避免存储手柄。我的函数是回调
猜你喜欢
  • 2021-04-24
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多