我有一个任意的,大量的(50-1000)列表,分别代表X和Y坐标,我想将它们绘制在一个图中。
列表的长度不同,通常每个100-1000个元素。我得到的列表是成对的x和y坐标(请参见示例),但可以轻松地将它们转换为2xN数组。它们需要从头到尾按顺序绘制。每行分别。
是否可以将我的所有列表打包到matplotlib可以读取的一个(或两个; x和y)对象上?
此示例提供了所需的输出,但是在有大量数据时不方便使用。
我很高兴能利用numpy的解决方案。
http_proxy=http://wsa.arz.de:3128
https_proxy=http://wsa.arz.de:3128
我希望这样:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1,1)
x1 = [1,2,5] # usually much longer and a larger number of lists
y1 = [3,2,4]
x2 = [1,6,5,3]
y2 = [7,6,3,2]
x3 = [4]
y3 = [4]
for x, y, in zip([x1, x2, x3],[y1, y2, y3]):
ax.plot(x,y, 'k.-')
plt.show()
答案 0 :(得分:1)
您可以为此使用LineCollection
。不幸的是,如果您想在行中添加标记,LineCollection
不支持该标记,因此您需要做一些技巧,例如在顶部添加一个散点图(请参见Adding line markers when using LineCollection)。
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
fig, ax = plt.subplots(1,1)
x1 = [1,2,5]
y1 = [3,2,4]
x2 = [1,6,5,3]
y2 = [7,6,3,2]
x3 = [4]
y3 = [4]
# Add lines
X = [x1, x2, x3]
Y = [y1, y2, y3]
lines = LineCollection((list(zip(x, y)) for x, y in zip(X, Y)),
colors='k', linestyles='-')
ax.add_collection(lines)
# Add markers
ax.scatter([x for xs in X for x in xs], [y for ys in Y for y in ys], c='k', marker='.')
# If you do not use the scatter plot you need to manually autoscale,
# as adding the line collection will not do it for you
ax.autoscale()
plt.show()
如果要使用数组,还可以执行以下操作:
import numpy as np
# ...
X = [x1, x2, x3]
Y = [y1, y2, y3]
lines = LineCollection((np.stack([x, y], axis=1) for x, y in zip(X, Y)),
colors='k', linestyles='-')
ax.add_collection(lines)
ax.scatter(np.concatenate(X), np.concatenate(Y), c='k', marker='.')