Reputation: 187
I have a plot in MATLAB that I would like to transform into a colormap (plot shown below). There are several line segments in this plot, and I want each line segment to be colored based on a specific value that is associated with the segment.
For example:
Value of line 1 = 800, plot a specific color
Value of line 2 = 555, plot a specific color ...etc.
Does anyone know how to do this? I have included the part of the code in my program that is making the plots below. In the code I want the color of the line to be dependent on ElementMap(i,6). I don't have a particular preference on the colors as long as I can tell which line segments have a higher value.
Thanks
%% Plot
for i = 1:length(ElementMap)
if ElementMap(i,6) < 1000
x = [ElementMap(i,1);ElementMap(i,3)];
y = [ElementMap(i,2);ElementMap(i,4)];
plot(x,y,['-','b','o']);
hold on;
end
end
Upvotes: 0
Views: 351
Reputation: 65430
You could determine an indexed color for each unique value in the 6th column and then convert these indexed colors to RGB colors using a colormap of your choosing (here we use parula
). Then when plotting each line, specify the Color
property.
% Get indices to use for the colormap
[~, ~, ind] = unique(ElementMap(:,6));
% Create a colormap of the correct size
cmap = parula(max(ind));
% Create a color for each plot
colors = ind2rgb(ind, cmap);
% Now plot everything
for k = 1:size(ElementMap, 1)
x = [ElementMap(k,1);ElementMap(k,3)];
y = [ElementMap(k,2);ElementMap(k,4)];
plot(x,y, 'Marker', 'o', 'LineStyle', '-', 'Color', colors(k,:));
hold on
end
With this approach, the colors won't necessary scale linearly with your data, but each unique value in ElementMap(:,6)
will be represented by a different color and smaller values will be differentiated from larger values.
If you don't care about every plot having a unique value, you could do something like the following which would get you a linear mapping between your colors and values.
values = ElementMap(:,6);
% Assign an index to each
ind = gray2ind(mat2gray(values))
% Create the colormap
cmap = parula(numel(unique(inds)));
% Create a color for each plot
colors = ind2rgb(ind, cmap);
% Now plot everything
for k = 1:size(ElementMap, 1)
x = [ElementMap(k,1);ElementMap(k,3)];
y = [ElementMap(k,2);ElementMap(k,4)];
plot(x,y, 'Marker', 'o', 'LineStyle', '-', 'Color', colors(k,:));
hold on
end
% Now create a colorbar
colorbar()
% Set the range of the colorbar
set(gca, 'CLim', [min(values), max(values)])
Upvotes: 1