Matplotlib 如何避免图例中的某些功能?

Matplotlib 如何避免图例中的某些功能?,matplotlib,Matplotlib,我需要在每次单击按钮(我使用的是pyqt4)时将一行包含到图形中,这一行必须被标记,并且我还需要将这些行与常量函数进行比较。以下是我尝试过的: labels = [] fig = plt.figure() ax = fig.add_subplot(111, axisbg='white') ax.hold(True) def function(k): x = np.linspace(0, 2, 100) y = np.sin(k * np.pi * x) * np.exp(-5 *

我需要在每次单击按钮(我使用的是pyqt4)时将一行包含到图形中,这一行必须被标记,并且我还需要将这些行与常量函数进行比较。以下是我尝试过的:

labels = []
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)

def function(k):
   x = np.linspace(0, 2, 100)
   y = np.sin(k * np.pi * x) * np.exp(-5 * x)
   labels.append('k = {}'.format(k))
   ax.plot(x, y)
   # reference line
   plt.axhline(y=0.1, c='k', linestyle='--')
   plt.legend(labels)

for i in range(0,5):
   function(i)

plt.show()
结果是:


有一种简单的方法可以跳过图例框中的常量线标记?

这是因为绘图中实际上有10条线,但图例仅显示5个标签。如果您通过将标签放入
plot
axhline
命令中进行检查,则如下所示

def function(k):
    x = np.linspace(0, 2, 100)
    y = np.sin(k * np.pi * x) * np.exp(-5 * x)
    ax.plot(x, y, label='k = {}'.format(k))
    # reference line
    ax.axhline(y=0.1, c='k', linestyle='--', label='reference')
    ax.legend()
    print "number of lines in plot: {}".format(len(ax.lines))
由于将设置为True,因此不会清除轴,但每次调用这些命令时都会向轴对象添加一条新线。这可能会更快,但您必须小心避免添加重复的艺术家。一个简单的解决方案是将图形拆分为两个函数:一个用于创建空绘图,另一个用于添加直线

import matplotlib.pyplot as plt
import numpy as np

def init_plot(ax):
    ax.hold(True)
    ax.axhline(y=0.1, c='k', linestyle='--', label='reference')
    ax.legend()

def add_line(ax, k):
    x = np.linspace(0, 2, 100)
    y = np.sin(k * np.pi * x) * np.exp(-5 * x)
    ax.plot(x, y, label='k = {}'.format(k))
    ax.legend()    

def main():
    fig = plt.figure()
    ax = fig.add_subplot(111, axisbg='white')

    init_plot(ax)
    for i in range(0,5):
        add_line(ax, i)

    plt.show()
    #raw_input('please press enter\n') # for OS-X

if __name__ == "__main__":
    main()

我建议您阅读,当然。

可能我没有遵循,但它看起来不像您的参考线axhline(y=0.1,…)包含在图例中

我会单独设置,没有理由每次绘制新线时都重新绘制。还可以尝试在
绘图
函数中传递
标签

fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)
# reference line - only draw this once
plt.axhline(y=0.1, c='k', linestyle='--')

def function(k):
   x = np.linspace(0, 2, 100)
   y = np.sin(k * np.pi * x) * np.exp(-5 * x)
   ax.plot(x, y, linestyle='-', label='k = {}'.format(k)) # set label attribute for line

for i in range(0,5):
   function(i)

plt.legend() # you only need to call this once, it will generate based on the label assigned to line objects
plt.show()

注意:如果您想以交互方式进行此操作(即按下按钮绘制),则必须先调用
plt.legend()
并在添加每一行新行后调用
plt.draw()
,这样它将更新图例。

对不起,我的问题可能不清楚,但是你的回答解决了这个问题,并给了我一个提示来改进我项目的其他绘图功能。非常感谢你。