根据第3个值更改2D绘图线的颜色

JSZ*_*JSZ 8 matlab plot colors matlab-figure colormap

我有一个看起来像这样的数据集

 140400 70.7850 1
 140401 70.7923 2
 140402 70.7993 3
 140403 70.8067 4
 140404 70.8139 5
 140405 70.8212 3
Run Code Online (Sandbox Code Playgroud)

在第一列对应于时间(数据点之间的一秒间隔)并且将在x轴上的情况下,第二列对应于距离并且将在y轴上.第三列是一个数字(一到五),是运动的资格.

我想制作一个图表,根据前一个数据点的数量改变两点之间的线条颜色.例如,我希望第一个和第二个数据点之间的行为红色,因为限定值为1.

我已经看过很多关于根据强度值制作颜色滑动比例的帖子,但我只想要5种颜色:(红色,橙色,黄色,绿色和蓝色).

我尝试过这样的事情:

plot(x,y,{'r','o','y','g','b'})
Run Code Online (Sandbox Code Playgroud)

但没有运气.

有关如何处理此问题的任何想法?如果可能的话没有循环.

Hok*_*oki 10

您也可以使用与2014b之前的Matlab版本一起工作的技巧(至少可以追溯到2009a).
但是,永远不会像你期望的那样简单(除非你为这里的一个解决方案编写一个包装器,你可以忘记plot(x,y,{'r','o','y','g','b'})).

诀窍是使用surface而不是line对象.曲面受益于它们的CData属性以及许多有用的功能来利用颜色贴图和纹理.

Matlab surf不处理1D数据,它需要一个矩阵作为输入,所以我们只需要复制每个坐标集(例如xx=[x,x]).
不过不用担心,表面会像线条一样薄,所以最终的结果并不难看.

%% // your data
M=[140400 70.7850 1
 140401 70.7923 2
 140402 70.7993 3
 140403 70.8067 4
 140404 70.8139 5
 140405 70.8212 3];

x = M(:,1) ; %// extract "X" column
y = M(:,2) ; %// same for "Y"
c = M(:,3) ; %// extract color index for the custom colormap

%% // define your custom colormap
custom_colormap = [
    1  0 0 ; ... %// red
    1 .5 0 ; ... %// orange
    1  1 0 ; ... %// yellow
    0  1 0 ; ... %// green
    0  0 1 ; ... %// blue
    ] ;

%% // Prepare matrix data
xx=[x x];           %// create a 2D matrix based on "X" column
yy=[y y];           %// same for Y
zz=zeros(size(xx)); %// everything in the Z=0 plane
cc =[c c] ;         %// matrix for "CData"

%// draw the surface (actually a line)
hs=surf(xx,yy,zz,cc,'EdgeColor','interp','FaceColor','none','Marker','o') ;

colormap(custom_colormap) ;     %// assign the colormap
shading flat                    %// so each line segment has a plain color
view(2) %// view(0,90)          %// set view in X-Y plane
colorbar
Run Code Online (Sandbox Code Playgroud)

会得到你:
cmapline


作为更一般情况的一个例子:

x=linspace(0,2*pi);
y=sin(x) ;

xx=[x;x];
yy=[y;y];
zz=zeros(size(xx));

hs=surf(xx,yy,zz,yy,'EdgeColor','interp') %// color binded to "y" values
colormap('hsv')
view(2) %// view(0,90)
Run Code Online (Sandbox Code Playgroud)

会给你一个正弦波,其颜色与y值相关联:
cmapline2


the*_*alk 7

你有Matlab R2014b或更高版本吗?

然后你可以使用Yair Altman介绍的一些未记录的功能:

n = 100;
x = linspace(-10,10,n); y = x.^2;
p = plot(x,y,'r', 'LineWidth',5);

%// modified jet-colormap
cd = [uint8(jet(n)*255) uint8(ones(n,1))].' %'

drawnow
set(p.Edge, 'ColorBinding','interpolated', 'ColorData',cd)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述