首页 > 解决方案 > 在一个 plot() 中绘制多条线时,Pyplot 返回不同的对象

问题描述

我想使用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)(注意缺少对地址的引用!)。但是,如果您仅在 a 中绘制单行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()

标签: pythonpython-2.7matplotlib

解决方案


推荐阅读