”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何为 10 个连续点的每段绘制不同颜色的线?

如何为 10 个连续点的每段绘制不同颜色的线?

发布于2024-11-14
浏览:847

How to Plot a Line with Varying Colors for Each Segment of 10 Consecutive Points?

用不同的颜色绘制一条线

问题陈述

给定两个列表,latt和lont,目标是绘制一条线,其中每个列表10 个连续点的线段以不同的方式表示color.

解决方案

线段数量有限

如果线段数量较少,例如10个或更少,一个简单的方法就是使用循环以唯一的颜色绘制每个段。

import numpy as np
import matplotlib.pyplot as plt

# Generate random colors
def uniqueish_color():
    return plt.cm.gist_ncar(np.random.random())

# Plot the line segments
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()

大量线段

对于大量线段,使用循环可能会很慢。相反,创建一个 LineCollection 对象。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

# Generate the line segments
xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

# Create a LineCollection object
fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)

# Set the color array
coll.set_array(np.random.random(xy.shape[0]))

# Add the LineCollection to the axes
ax.add_collection(coll)
ax.autoscale_view()

# Display the plot
plt.show()

选择颜色

对于这两种方法,我们使用“gist_ncar”颜色图来生成独特的颜色。有关其他颜色图选项,请参阅此页面:http://matplotlib.org/examples/color/colormaps_reference.html

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3