python:如何用不同的颜色绘制一条线 [英] python: how to plot one line in different colors
问题描述
我有两个列表如下:
latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]
lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]
现在我想将其绘制为一条线,将这些latt"和lont"记录中的每 10 个分隔为一个句点,并为其赋予独特的颜色.我该怎么办?
now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and give it a unique color. what should I do?
推荐答案
有几种不同的方法可以做到这一点.最佳"方法主要取决于您要绘制的线段数量.
There are several different ways to do this. The "best" approach will depend mostly on how many line segments you want to plot.
如果您只想绘制少量(例如 10 个)线段,那么只需执行以下操作:
If you're just going to be plotting a handful (e.g. 10) line segments, then just do something like:
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
.例如
If you're plotting something with a million line segments, though, this will be terribly slow to draw. In that case, use a LineCollection
. E.g.
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
For both of these cases, we're just drawing random colors from the "gist_ncar" coloramp. Have a look at the colormaps here (gist_ncar is about 2/3 of the way down): http://matplotlib.org/examples/color/colormaps_reference.html
这篇关于python:如何用不同的颜色绘制一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!