有几种不同的方法可以实现这一点。 "最佳"方法主要取决于您想绘制多少条线段。
如果您只需要绘制几条(例如10条)线段,则可以执行以下操作:
import numpy as np
import matplotlib.pyplot as plt
def uniqueish_color():
"""There're better ways to generate unique colors, but this isn't awful."""
return plt.cm.gist_ncar(np.random.random())
xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0)
fig, ax = plt.subplots()
for start, stop in zip(xy[:-1], xy[1:]):
x, y = zip(start, stop)
ax.plot(x, y, color=uniqueish_color())
plt.show()
![enter image description here](https://istack.dev59.com/CA3gu.webp)
如果你要绘制的图形有一百万条线段,那么使用该方法会非常缓慢。在这种情况下,可以使用LineCollection
。例如:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])
fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))
ax.add_collection(coll)
ax.autoscale_view()
plt.show()
![图片描述](https://istack.dev59.com/WIgP9.webp)
对于这两种情况,我们只是从“gist_ncar”颜色图中随机选择颜色。在这里查看调色板(gist_ncar大约在页面的2/3处):http://matplotlib.org/examples/color/colormaps_reference.html
scatter
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter - tacaswell