Matplotlib 绘制一条连续改变颜色的线 [英] Matplotlib plotting a single line that continuously changes color

查看:124
本文介绍了Matplotlib 绘制一条连续改变颜色的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在(x,y)平面上绘制一条曲线,曲线的颜色取决于另一个变量T的值.x是一维numpy数组,y是一维numpy数组.

I would like to plot a curve in the (x,y) plane, where the color of the curve depends on a value of another variable T. x is a 1D numpy array, y is a 1D numpy array.

T=np.linspace(0,1,np.size(x))**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)

我希望线条根据 T 的值从蓝色变为红色(使用 RdBu 颜色图)(每个 (x,y) 对都存在一个 T 值).

I want the line to change from blue to red (using RdBu colormap) depending on the value of T (one value of T exists for every (x,y) pair).

我找到了这个,但我不知道如何将它变形为我的简单示例.我将如何将 linecollection 用于我的示例?http://matplotlib.org/examples/pylab_examples/multicolored_line.html

I found this, but I don't know how to warp it to my simple example. How would I use the linecollection for my example? http://matplotlib.org/examples/pylab_examples/multicolored_line.html

谢谢.

推荐答案

一个想法可能是使用 color=(R,G,B) 设置颜色,然后将您的情节拆分为 n 个段,并连续改变R,G或B(或组合)之一

One idea could be to set the color using color=(R,G,B) then split your plot into n segments and continuously vary either one of the R, G or B (or a combinations)

import pylab as plt
import numpy as np

# Make some data
n=1000
x=np.linspace(0,100,n)
y=np.sin(x)

# Your coloring array
T=np.linspace(0,1,np.size(x))**2
fig = plt.figure()
ax = fig.add_subplot(111)

# Segment plot and color depending on T
s = 10 # Segment length
for i in range(0,n-s,s):
    ax.plot(x[i:i+s+1],y[i:i+s+1],color=(0.0,0.5,T[i]))

希望对你有帮助

这篇关于Matplotlib 绘制一条连续改变颜色的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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