可以通过多种方法来绘制具有不同颜色的线。首选方法取决于要渲染的线段数量。
对于少量线段(例如,少于 10 条),以下方法就足够了:
<code class="python">import numpy as np import matplotlib.pyplot as plt # Define line segment data xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0) # Create figure and axes fig, ax = plt.subplots() # Iterate through line segments for start, stop in zip(xy[:-1], xy[1:]): x, y = zip(start, stop) ax.plot(x, y, color=np.random.rand(3)) plt.show()</code>
对于大量线段(例如超过一千个),LineCollections 提供了更高效的解决方案:
<code class="python">import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection # Define line segment data xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0) # Reshape data into segments xy = xy.reshape(-1, 1, 2) segments = np.hstack([xy[:-1], xy[1:]]) # Create figure and axes fig, ax = plt.subplots() # Create LineCollection with random colors coll = LineCollection(segments, cmap=plt.cm.gist_ncar) coll.set_array(np.random.random(xy.shape[0])) # Add LineCollection to axes ax.add_collection(coll) ax.autoscale_view() plt.show()</code>
两种方法都依赖于从“gist_ncar”coloramp 中随机选择颜色。如需更多选择,请参阅:http://matplotlib.org/examples/color/colormaps_reference.html
以上是如何在 Matplotlib 中绘制彩色线段?的详细内容。更多信息请关注PHP中文网其他相关文章!