Reputation: 548
I need to assign certain colors to certain dots of a scatter plot. I've written something like this:
Color = zeros(size(Check,1),1);
for i = 1:size(Check,1)
if Check(i) == 0
Color(i) = [0.3010 0.7450 0.9330];
elseif Check(i) == 1
Color(i) = [0.4660 0.6740 0.1880];
elseif Check(i) == 2
Color(i) = [0.9290 0.6940 0.1250];
elseif Check(i) == 3
Color(i) = [0.8500 0.3250 0.0980];
elseif Check(i) == 4
Color(i) = [0.6350 0.0780 0.1840];
end
end
scatter(x,y,Color,'filled','s');
Beware that 'x', 'y', 'Color' and 'Check' have the same dimension (15000 x 1). Numbers in 'Check' are either '0', '1', '2', '3', or '4'. I just need to assign five different colors to my scatter plot based on the numbers I have in 'Check' matrix. The colors should be those that I used in the code as I need this plot to match with another bar chart I already have. Any help will be highly appreciated!
Upvotes: 0
Views: 1436
Reputation: 148
Scatter plots in MATLAB have the CData
property that can be used to assign colors to plots. This can be an nx3
matrix, as you have in your Color
variable. However, the CData
property can also be a vector, and you can use the colormap()
function!
Start off like adjpayot did:
Color = [0.3010 0.7450 0.9330;
0.4660 0.6740 0.1880;
0.9290 0.6940 0.1250;
0.8500 0.3250 0.0980;
0.6350 0.0780 0.1840];
% Assume you have a figure open already
scatter(x,y,'filled', 'CData', Check);
colormap(Color);
colorHandle = colorbar();
Upvotes: 2
Reputation: 173
You need Color
to be a Color = zeros(size(Check,1),3);
That is because colors are RGB values, so need one number for each colour channel.
this means the rest of your code needs to be:
Color = zeros(size(Check,1),3);
for i = 1:size(Check,1)
if Check(i) == 0
Color(i,) = [0.3010 0.7450 0.9330];
elseif Check(i) == 1
Color(i,:) = [0.4660 0.6740 0.1880];
elseif Check(i) == 2
Color(i,:) = [0.9290 0.6940 0.1250];
elseif Check(i) == 3
Color(i,:) = [0.8500 0.3250 0.0980];
elseif Check(i) == 4
Color(i,:) = [0.6350 0.0780 0.1840];
end
end
scatter(x,y,Color,'filled','s');
If you want you can also get rid of the loop by doing:
Color=[0.3010 0.7450 0.9330;
0.4660 0.6740 0.1880;
0.9290 0.6940 0.1250;
0.8500 0.3250 0.0980;
0.6350 0.0780 0.1840]
scatter(x,y,Color(Check+1,:),'filled','s');
In that code I'm using Check
to index the list of colours specified in Color
. Adding another case is as simple as adding an extra colour to the array.
Upvotes: 1