可以透過多種方法來繪製不同顏色的線條。首選方法取決於要渲染的線段數量。
對於少量線段(例如,少於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中文網其他相關文章!