matplotlib:改变线的颜色以捕获数据中的自然时间参数化 [英] matplotlib: varying color of line to capture natural time parameterization in data

查看:78
本文介绍了matplotlib:改变线的颜色以捕获数据中的自然时间参数化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变从两个数组中的数据绘制的线条的颜色(例如ax.plot(x,y)).颜色应随xy的索引的增加而变化.我实质上是试图捕获数组xy中数据的自然时间"参数化.

I am trying to vary the color of a line plotted from data in two arrays (eg. ax.plot(x,y)). The color should vary as the index into x and yincreases. I am essentially trying to capture the natural 'time' parameterization of the data in arrays x and y.

在一个完美的世界中,我想要类似的东西:

In a perfect world, I want something like:

fig = pyplot.figure()
ax  = fig.add_subplot(111)
x   = myXdata 
y   = myYdata

# length of x and y is 100
ax.plot(x,y,color=[i/100,0,0]) # where i is the index into x (and y)

产生一条颜色,从黑色到深红色,再到亮红色的线.

to produce a line with color varying from black to dark red and on into bright red.

我已经看到示例可以很好地绘制由某些时间"数组,但我无法将其用于原始数据...

I have seen examples that work well for plotting a function explicitly parameterized by some 'time' array, but I can't get it to work with raw data...

推荐答案

第二个示例是您想要的示例...我已经对其进行了编辑以适合您的示例,但更重要的是,请阅读我的评论以了解正在发生的情况:

The second example is the one you want... I've edited it to fit your example, but more importantly read my comments to understand what is going on:

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

x   = myXdata 
y   = myYdata
t = np.linspace(0,1,x.shape[0]) # your "time" variable

# set up a list of (x,y) points
points = np.array([x,y]).transpose().reshape(-1,1,2)
print points.shape  # Out: (len(x),1,2)

# set up a list of segments
segs = np.concatenate([points[:-1],points[1:]],axis=1)
print segs.shape  # Out: ( len(x)-1, 2, 2 )
                  # see what we've done here -- we've mapped our (x,y)
                  # points to an array of segment start/end coordinates.
                  # segs[i,0,:] == segs[i-1,1,:]

# make the collection of segments
lc = LineCollection(segs, cmap=plt.get_cmap('jet'))
lc.set_array(t) # color the segments by our parameter

# plot the collection
plt.gca().add_collection(lc) # add the collection to the plot
plt.xlim(x.min(), x.max()) # line collections don't auto-scale the plot
plt.ylim(y.min(), y.max())

这篇关于matplotlib:改变线的颜色以捕获数据中的自然时间参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆