如何在matplotlib中使用LineCollection添加或创建水平线?我试图使动画更快,并且不想越过老土,但基本上我想避免在for循环中使用axhline
来构造行数组。因此,建议我尝试LineCollection。但是到目前为止,我只能绘制一系列图。
import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]
lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()
如果我显式添加坐标,例如:
x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]
我得到以下情节?
这怎么可能呢?
最佳答案
一种选择是:
import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
y = [42,13,24,14,74,45,22,44,77]
segs = np.zeros((len(y), 2, 2))
segs[:,:,1] = np.c_[y,y]
segs[:,1,0] = np.ones(len(y))
fig, ax = plt.subplots()
lc = LineCollection(segs,color='blue', transform=ax.get_yaxis_transform())
ax.add_collection(lc)
ax.set_xlim(0,10)
ax.set_ylim(0,100)
plt.show()