当在一个plot()中绘制多条线时,Pyplot返回不同的对象

时间:2019-01-28 14:47:11

标签: python python-2.7 matplotlib

我想将fig.legend与多个标签一起使用。示例https://matplotlib.org/examples/pylab_examples/figlegend_demo.html建议我应该在单个ax.plot(...)调用中绘制所有内容,然后将句柄作为元组传递给fig.legend(...)

但是我有9条单独的行,我想循环生成它们。如果先启动handles = [],然后依次handles.append(...)所有行,则会收到类似UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x2ba353491f50>] instances.

的错误消息

在调查后,我发现上面链接中的示例生成了python调用Lines2D(_line0) Line2D(_line1)的对象(请注意缺少对地址的引用!)。但是,如果您仅在plot(...)中绘制一行,则python会参考地址生成这些对象。

最小示例:

### This is the one from the link, with additional 'print's

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])

x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1, l2 = ax1.plot(x, y1, 'rs-', x, y2, 'go')
print l1, l2

y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax2.plot(x, y3, 'yd-', x, y4, 'k^')

fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')
fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
plt.show()

### This is the modified one with the lines plotted individually

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])

x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1 = ax1.plot(x, y1, 'rs-')
l2 = ax1.plot(x, y2, 'go')
print l1, l2

y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax2.plot(x, y3, 'yd-', x, y4, 'k^')

### Will produce the warning here:
fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')

fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
### Final plot will contain an empty legend at the top left
plt.show()

0 个答案:

没有答案