python - 在一个 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()
解决方案
推荐阅读
- python - 如何根据 M2M 关系在 django 模型中自动填充 IntegerField?
- java - 使用复合键的 JPA 多对一映射
- javascript - react-beautiful-dnd:拖放列表时防止闪烁
- css - 修改 AG-grid cell 工具提示的 z-index
- javascript - 如何使用 reactjs 在 webapps 上获取特定的移动设备型号?
- jquery - 如何在jQuery中手动将表单设置为无效
- zabbix - 邮件警报中的 Ping 平均值
- json - json自适应卡中容器迭代内的条件($when)
- python - 不能在列表中使用 random.choice() 函数?
- perl - 如何在 perl 中使用 bash 的 grep?