python不同颜色,Python:如何以不同的颜色绘制一条线

这篇博客介绍了如何使用Python的matplotlib库绘制多个线段,并为每个线段分配独特的颜色。对于少量线段,可以逐个设置颜色;而对于大量线段,推荐使用LineCollection以提高效率。示例中展示了两种情况:一种是手动为每一对坐标点绘制线段,另一种是通过LineCollection批量绘制。同时,文章提供了颜色映射的选择和生成随机颜色的方法。
摘要由CSDN通过智能技术生成

I have two list as below:

latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]

lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]

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.

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()

CA3gu.png

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()

WIgP9.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值