如何用不同的颜色绘制一条线
- 2025-01-13 08:52:00
- admin 原创
- 130
问题描述:
我有以下两个列表:
latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]
lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]
现在我想将其绘制为一条线,将每 10 条“latt”和“lont”记录分隔为一个句点,并赋予其独特的颜色。我该怎么做?
解决方案 1:
有几种不同的方法可以做到这一点。“最佳”方法主要取决于您要绘制多少条线段。
如果你只是要绘制一些(例如 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()
但是,如果你要绘制包含一百万条线段的图形,绘制速度会非常慢。在这种情况下,请使用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)
# Reshape things so that we have a sequence of:
# [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],...]
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()
对于这两种情况,我们只是从“gist_ncar”颜色图中随机抽取颜色。请查看此处的颜色图(gist_ncar 位于下方约 2/3 处):http ://matplotlib.org/examples/color/colormaps_reference.html
解决方案 2:
从此示例复制:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
z = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative
# Create a colormap for red, green and blue and a norm to color
# f' < -0.5 red, f' > 0.5 blue, and the rest green
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be numlines x points per line x 2 (x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Create the line collection object, setting the colormapping parameters.
# Have to set the actual values used for colormapping separately.
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(z)
lc.set_linewidth(3)
fig1 = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(x.min(), x.max())
plt.ylim(-1.1, 1.1)
plt.show()
解决方案 3:
请参阅此处的答案以生成“周期”,然后使用@tcaswell 提到的matplotlib 散点函数。使用plot.hold函数可以绘制每个周期,颜色会自动递增。
解决方案 4:
抄袭了@JoeKington 的颜色选择,
import numpy as np
import matplotlib.pyplot as plt
def uniqueish_color(n):
"""There're better ways to generate unique colors, but this isn't awful."""
return plt.cm.gist_ncar(np.random.random(n))
plt.scatter(latt, lont, c=uniqueish_color(len(latt)))
您可以使用 来执行此操作scatter
。
解决方案 5:
我一直在寻找一个简短的解决方案,如何使用 pyplots 线图来显示由标签特征着色的时间序列,而不使用由于数据点数量而产生的散点图。
我想出了以下解决方法:
plt.plot(np.where(df["label"]==1, df["myvalue"], None), color="red", label="1")
plt.plot(np.where(df["label"]==0, df["myvalue"], None), color="blue", label="0")
plt.legend()
缺点是您要创建两个不同的线图,因此无法显示不同类别之间的联系。就我的目的而言,这不是什么大问题。它可能会帮助某些人。
解决方案 6:
根据@AndreS 的回答,
我这样做了。
# Start with a default color (whatever your 'main' color will be)
plt.plot(data, color="blue")
# re-plot the line segments you want to be red
plt.plot(np.where(red==True, data, None), color="red")
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD