MATLAB Answers

Hekseli
0

Define colormap according to certain variable.

Asked by Hekseli
on 23 Oct 2013
Latest activity Commented on by Walter Roberson
on 8 Aug 2019
Hey!
I have hundreds of 2D-curves in one plot. Curves are produced by function where is a random variable. Now I would like to specify that the curves are displayed with different colors with respect to the value of a used random variable.
What is the proper way to manage this?

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Hekseli
on 24 Oct 2013

Thanks. I solved this in a following way!
%Defining a colormap
CMap=colormap(jet(nsamples));
%Sorting the initial y-coordinates for colormap (So colors depend on the initial y coordinate of a particular curve. Could be some other variable too.)
init_Y_p_sorted=sort(Y_p(1,:));
%Plotting curve by curve in a loop
for j=1:nsamples
ph=plot(X_p(:,j), Y_p(:,j));
%Find the sorted index of a initial coordinate
CMap_ind=find(init_Y_p_sorted==Y_p(1,j));
set(ph,'Color',CMap(CMap_ind,:));
hold on;
Only problem is that if nsamples is a large number, then the colorbar of the figure becomes totally black so somekind of bining should be still added.

  3 Comments

Thanks
it does not work. What is Color ??
The only reference to Color there is in the set(ph) call. ph is the result of the plot() call, so ph will be a graphics handle to a lineseries object, and the set() call will be setting the line color of the lineseries object.

Sign in to comment.


Answer by Jonathan LeSage on 23 Oct 2013

You can define a colormap using the hsv function and then define the color of each line according to the random variable that you mention. If you have a vector of the random variables prior to plotting, you can group them via histc and then use the different bin counts to determine which color to assign each line.
If your random numbers are already integers, the problem becomes fairly straightforward. Here is some example code demonstrating the general procedure you might want to try!
% Generate arbitrary random variables
numRandom = 10;
rangeInts = [1 5];
randomVariables = randi(rangeInts,numRandom,1);
% Generate 5 hue-saturation-value color map for your data
% Each row of 'colorVec' defines a different RGB color for you lines
colorVec = hsv(numRandom);
% Define Arbitrary Function for Plotting
xVec = 0:0.1:10;
hold on;
for i = 1:numRandom,
% Arbitrary function which relies on the random variable
yVec = randomVariables(i)*xVec + randn(1,numel(xVec));
% Plot line with color selected by random number
plot(xVec,yVec,'Color',colorVec(randomVariables(i),:))
end
hold off;
Hope this helps you to get started!

  0 Comments

Sign in to comment.