MATLAB Answers

How can I change the line color in a 2D graph using colormap?

303 views (last 30 days)
alex mango
alex mango on 23 Apr 2018
Commented: Star Strider on 25 Apr 2018
Hello everyone,
there is a mx5 matrix composed by the following columns:
x1 y1 x2 y2 c
where (x1,y1) and (x2,y2) are respectively the initial e and final coordinates of a link; c is the "color" variable.
I would like to assign a different color to the links according to c, using colormap.
I have already adopted the following solution:
A = rand(10,5);
c = A(:,5);
for i=1:10
x1=A(i,1);
y1=A(i,2);
x2=A(i,3);
y2=A(i,4);
plot([x1,x2],[y1,y2],'Color', [c(i) 0.2*(1-c(i)) 0.3*(1-c(i))])
hold on
end
The result is not satisfying. I would like to use the default colormap, but I know that is not possible to use it with plot. Does anybody know if it is possible to use surf? And how?
I need it for my thesis, any help is appreciated. Thanks a lot! :)

  0 Comments

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 23 Apr 2018
I am not certain what result you want.
Try this:
A = rand(10,5);
cm = colormap(parula(size(A,1))); % Default Colormap
% c = A(:,5);
for i=1:10
x1=A(i,1);
y1=A(i,2);
x2=A(i,3);
y2=A(i,4);
plot([x1,x2],[y1,y2],'Color', cm(i,:))
hold on
end

  6 Comments

Show 3 older comments
Star Strider
Star Strider on 24 Apr 2018

I still have no idea what you want.

This creates a random matrix, then colours every line defined by the first 4 columns with the colour defined for it in the 5-th column. Note that the 5-th column must be an integer for this to work, so if they are not, you have to define them as integers. The unique function will do that.

Example

M = rand(20, 5);                                                    % Create Matrix
[Cu,~,Idx] = unique(M(:,5), 'stable');                              % Find Unique Elements Of Col #5, Return Index, Don’t Sort
cm = colormap(jet(max(Idx)));                                       % Define ‘colormap’
figure(1)
for k1 = 1:size(M,1)
    plot(M(k1,[1 3]), M(k1,[2 4]), 'Color',cm(Idx(k1),:), 'LineWidth',2)
    hold on
end
alex mango
alex mango on 25 Apr 2018
That's exactly what I wanted. Thank you very much for your help and for your patience.
Star Strider
Star Strider on 25 Apr 2018
As always, my pleasure.
If my Answer helped you solve your problem, please Accept it!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!