phdstudent
phdstudent

Reputation: 1144

Matlab - Colour markers in plot according to criteria

I have a quick question on a matlab plot. I want to draw a line with round markers on each point, but I want the markers to have a different color according to some criteria. I managed to display on the markers the different criteria but I was not able to change their colours.

To be more specific on the code below:

What I want is the markers with criteria 1 to be in one colour, markers with criteria 2 to be with another colour, and so on and so forth.

The code below plots the line with the markers and with the criteria inside the markers.

% plot the data
figure
d3 = vals;
n = 1:numel(d3);
plot(n,d3, '-ob','markersize',10,'markerfacecolor','w');
for idx = 1:numel(d3)
    text(n(idx),d3(idx), num2str(RiskierInd(idx)),...
         'FontSize',8,...
         'HorizontalAlignment','center');
end

enter image description here

I did check this post which is similar, but couldn't figure out how to implement it.

Also, is it possible to add a legend with the color of the markers afterwards?

Upvotes: 1

Views: 2293

Answers (1)

LowPolyCorgi
LowPolyCorgi

Reputation: 5171

You can use scatter instead of plot for this. You can replace

plot(n,d3, '-ob','markersize',10,'markerfacecolor','w');

with

hold on
plot(n, d3,'b-');
scatter(n, d3, [], RiskierInd, 'filled');
caxis([1 12]);

Then, to display the correspondence between the colors and the values you can simply add colorbar to your code.

Edit If you want to define custom colors, you can use colormap with a custom n-by-3 array of RGB colors. For instance, to have exactly 12 colors you can do:

 colormap(jet(12));

Best,

Upvotes: 1

Related Questions