CodeFusionMobile
CodeFusionMobile

Reputation: 15110

How to show color gradient on scatter plot in matlab?

I have a scatter plot that will overlay several sets of data. Each set of data currently displays as the next color in the default colormap. This is my code right now:

figure
hold on
for i=1:10
   scatter(RunRawArea(i,:), RunRawNetLength(i,:));
end
hold off

What i would like is to color code each set of data (indexed by i) to be the next color on a gradient. For example, the data for i=1 would be blue, i=5 would be purple, and i=10 would be red.

How could I do this?

Upvotes: 3

Views: 8470

Answers (2)

EBH
EBH

Reputation: 10450

Method 1:

You can vectorize your data, so you don't need a loop and than add a color by series:

% specify your color map:
colorCode = lines(size(RunRawNetLength,1)); % or any other colormap...
% define the correct color for each series:
coloVev = repmat(colorCode,size(RunRawNetLength,1),1);
% plot it all at once without a loop:
scatter(RunRawArea(:),RunRawNetLength(:),[],coloVev)

Method 2:

If you have the Statistics and Machine Learning Toolbox you can also do this with gscatter:

% define the series of data:
group = repmat(1:size(RunRawNetLength,1),1,size(RunRawNetLength,1));
% plot it all at once without a loop:
gscatter(RunRawArea(:),RunRawNetLength(:),group,colorCode);

if your colormap has not enough colors for all the series, then the function loops over and start from the first one.

Result:

In both cases the result for some random data will be (the main difference is that gscatter fill the data points and add the legend by default):

gscatter demo

Note that I used the colormap lines which has only 7 entries, so in this example with 10 series it repeats itself.

Upvotes: 0

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

You should add another parameter to scatter - called CData

https://www.mathworks.com/help/matlab/ref/scatter.html

Description: scatter(x,y) creates a scatter plot with circles at the locations specified by the vectors x and y. This type of graph is also known as a bubble plot.

In your example:

figure
hold on
colorVec = linspace(1,0, size(RunRawNetLength,1));
colorVec = transpose(colorVec);
colorVec = repmat(colorVec,[1 3]);
for i=1:10
   scatter(RunRawArea(i,:), RunRawNetLength(i,:),'CData', colorVec );
end
hold off

Upvotes: 1

Related Questions