在 matplotlib 中,可以通过多种方法来绘制具有不同颜色段的线。选择取决于要绘制的线段数量。
如果只需要几条线段,如绘制轨迹,请考虑以下事项:
<code class="python">import numpy as np import matplotlib.pyplot as plt # Generate random data xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0) fig, ax = plt.subplots() # Plot each line segment with a unique color for start, stop in zip(xy[:-1], xy[1:]): x, y = zip(start, stop) ax.plot(x, y, color=plt.cm.gist_ncar(np.random.random())) plt.show()</code>
处理大量线段时,更有效的方法是使用 LineCollection。
<code class="python">import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection # Generate random data xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0) # Reshape data for compatibility with LineCollection xy = xy.reshape(-1, 1, 2) segments = np.hstack([xy[:-1], xy[1:]]) fig, ax = plt.subplots() # Create a LineCollection with randomly assigned colors coll = LineCollection(segments, cmap=plt.cm.gist_ncar) coll.set_array(np.random.random(xy.shape[0])) # Add the LineCollection to the plot ax.add_collection(coll) ax.autoscale_view() plt.show()</code>
在这两种方法中,可以参考 Matplotlib 文档更改所选的颜色图。
以上是如何在 Matplotlib 中绘制不同颜色的线条?的详细内容。更多信息请关注PHP中文网其他相关文章!