MATLAB: Colormap for plot function

colorbarcolormaplinesplot

Hi, I'm trying to to create my own Finite Element solver and I have a problem with colouring of lines (elements) according to stress inside. I found out that colormap is not originally supported for plot function. Is there any possibility how to do it ?
Lines represents "elements" with width according to cross-sectional area. I would like to color each line according to matrix "stress" (first column is number of element, second column is stress in current element) and colorbar under the plot. Something like this:
HMoiN0z.png
Here is my code, thanks in advance for help.
L = 6000; % length of construction [mm]
H = 1299; % height of construction [mm]
D0=30; % initial diameter of element [mm]
%positions of nodes 1-9
nodes = [0 0; L/4 0; L/2 0; 3*L/4 0; L 0; L/8 H; 3*L/8 H; 5*L/8 H; 7*L/8 H];
%connections of nodes
elements = [1 2; 1 6; 2 6; 2 3; 2 7; 3 7; 3 4; 3 8; 4 8; 4 5; 4 9; 5 9; 6 7; 7 8; 8 9];
%cross-sectional areas of elements
S=zeros(size(elements,1),1);
S(:,1)=(pi*D0^2/4);
%Calculated Stress matrix (first column - number of element
%second column - stress in element [MPa])
Stress=[1.0000 40.8404;2.0000 -81.6790; 3.0000 81.6790;4.0000 122.5211;5.0000 -81.6790;6.0000 81.6790;7.0000 122.5211;8.0000 81.6790;9.0000 -81.6790;10.0000 40.8404;11.0000 81.6790;12.0000 -81.6790;13.0000 -81.6808;14.0000 -163.3615;15.0000 -81.6808];
figure(1)
hold on
for i=1:size(elements,1)
x=[nodes(elements(i,1),1) nodes(elements(i,2),1)];
y=[nodes(elements(i,1),2) nodes(elements(i,2),2)];
plot(x,y,'Color',[0 0 1]','LineWidth', sqrt(4*S(i)/pi)/5)
end
axis equal
title 'Shape and Stress '
hold off

Best Answer

"I found out that colormap is not originally supported for plot function."
The axes/figure colormap is used for patches and images (e.g. surf, image, etc.).
The axes/figure colormap is NOT used for line objects (e.g. plot).
"Is there any possibility how to do it ?"
You can either
1. set the ColorOrder property of the axes:
The ColorOrder property determines the colors of line objects (e.g. plot). It is a little tricky to use because high-level functions (e.g. plot) reset this property. But it can be done, see my FEX submission for examples:
2. generate a colormap and use indexing to select colors:
num = 64;
mat = cool(num);
tmp = Stress(:,2);
idx = round(interp1([min(tmp),max(tmp)],[1,num],tmp));
hold on
for i=1:size(elements,1)
x=[nodes(elements(i,1),1) nodes(elements(i,2),1)];
y=[nodes(elements(i,1),2) nodes(elements(i,2),2)];
plot(x,y,'Color',mat(idx(i),:),'LineWidth', sqrt(4*S(i)/pi)/5)
end
axis equal
which plots this:
If you do not like cool colormap then you can select one from the inbuilt colormaps:
or download a FEX submission:
or generate your own colormap.
To add the colorbar use the colorbar function and specify its location option:
Related Question