How to set for each point a different color

308 views (last 30 days)
Hello,
How do I set the color for points by plot,
I want to have for example 1000 points, each point is different color.
Thanks.

Accepted Answer

Image Analyst
Image Analyst on 1 Mar 2014
You can use scatter and pass in the color for each point. See this demo:
% Demo to very color of scatterpoints depending on their location
clc;
clear
x = rand(1000,1);
y = rand(1000,1);
distances = ((x-.5).^2 + (y-0.5).^2).^0.5;
% Normalize - divide my sqrt(maxX^2 + maxY^2)
distances = distances / sqrt(.5^2 + .5^2);
[sortedDistances sortIndexes] = sort(distances);
% Arrange the data so that points close to the center
% use the blue end of the colormap, and points
% close to the edge use the red end of the colormap.
xs = x(sortIndexes);
ys = y(sortIndexes);
cmap = jet(length(x)); % Make 1000 colors.
scatter(xs, ys, 10, cmap, 'filled')
grid on;
title('Points where color depends on distance from center', ...
'FontSize', 30);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
  7 Comments
Walter Roberson
Walter Roberson on 22 Jul 2018
Brando is not the initial poster, and is asking about something slightly different that does not require the sorting and so on -- a way to be able to specify a color index for each point. Which is what already effectively happens if you pass a vector of values for color information.
Reflecting back, though, the code I posted does not truly treat the index vector as absolute indices into the color map. To do that with the colormap that is in effect, you would need:
numcolors = size(colormap(),1);
pointsize = 10;
scatter(x(:), y(:), pointsize, colorindex(:), 'filled');
caxis([1 numcolors])
assuming the index starts from 1 (which might not be the case for uint8 index information.)
Image Analyst
Image Analyst on 22 Jul 2018
Sorting was not necessary in my code. I just did that because it make the colors progress with distance in a pretty way. You could omit the sorting and just have unique colors randomly all over the place. You can make up cmap however you want. You don't have to use jet() or one of the other built in functions, you could make it up according to your own formula. You could even use the color map editor if you want. I still don't see why it's annoying or overly complicated.

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!