Graphs -how to change the color of a segment joining 2 dots multiple times in the same plot
1 次查看(过去 30 天)
显示 更早的评论
Hi all,
I am pretty new to MATLAB programming and I have a problem regarding graphing data. My data are contained in a [3xn] matrix, and I want to plot the first two lines in a xy graph, together with a connecting line. That's easy using the plot function. Things become more complicated when I want to change the color of the segment connecting two consecutive points as a function of the values contained in the third line. For example, if the value in a cell of the third line is <0.5 I want to draw the correspondent segment in black, and if it is >0.5 I want to draw it in red. Could anybody suggest how to do it? Thanks a lot!
0 个评论
回答(3 个)
the cyclist
2011-1-27
This is pretty ugly, with the looping, but it gives you the gist of one way of doing it. Basically, you assign a handle to each line segment, and use that handle to color the object depending on the third variable. (I split out the variables into three column vectors, to try to be a little clearer about the x-y plotting.)
function [] = dynamicPlotLineColor()
nSegments = 20;
x = rand(2*nSegments,1);
y = rand(2*nSegments,1);
c = rand(nSegments,1);
figure
hold on
for ns = 1:nSegments
hs = plot(x(2*ns-1:2*ns),y(2*ns-1:2*ns));
if c(ns)<0.5,
set(hs,'Color','k')
else
set(hs,'Color','r')
end
end
end
0 个评论
Vieniava
2011-1-27
% lets prepair input matrix
MAT=zeros(3,20);
MAT(3,:)=randi(1,20);
MAT(1,:)=1:20;
MAT(2,:)=MAT(1,:).^2;
% lets go
[k n]=size(MAT);
for i=2:n
if MAT(3,i)<0.5
C='r';
else
C='k';
end
line(MAT(1,[i-1 i]), MAT(2,[i-1 i]), 'Color', C);
end
0 个评论
Walter Roberson
2011-1-27
plot creates lineseries objects, which can also be manually created with line() . Any one line object is restricted to being a single colour. That is why the posters above break everything into individual line segments between the points rather than plotting the entire line at one go: it is the only way to control the color at that fine of a level.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Properties 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!