我在matplotlib中使用 LineCollection
快速绘制了大量不同颜色的线。但是,即使查看了LineCollection文档,我也找不到任何为线设置线标记的方法。使用LineCollection时,有什么办法可以设置线标记?
注意:不能使用pyplot.plot(),因为它对于我的用例来说太慢了,该用例绘制大约20万条线。
图解示例:
用于生成示例的代码(original source):
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
lc = LineCollection(lines, colors=['r', 'g', 'b'])
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.add_collection(lc)
ax1.autoscale()
ax1.set_title('Current')
# Doesn't seem to do anything
for l in ax1.lines:
l.set_marker('o')
ax2 = fig.add_subplot(1, 2, 2)
ax2.plot([0, 1], [1, 1], 'ro-')
ax2.plot([2, 3], [3, 3], 'go-')
ax2.plot([1, 1], [2, 3], 'bo-')
ax2.set_title('Goal')
plt.show()
最佳答案
我认为您不能将标记添加到LineCollection
。但是,使用ax.scatter
在LineCollection
顶部绘制标记可能比使用ax.plot
更快
例如,类似:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
colors = ['r', 'g', 'b']
lc = LineCollection(lines, colors=['r', 'g', 'b'])
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax1.add_collection(lc)
ax1.autoscale()
x = [i[0] for j in lines for i in j]
y = [i[1] for j in lines for i in j]
c = [col for col in colors for _ in (0, 1)]
ax1.scatter(x, y, c=c)
plt.show()