Search code examples
matlabmatlab-figurelegendscatter-plotcolormap

Matlab: How to set color of legend in a scatter plot where each data point gets a different color?


Here is the sample code:

x = rand(100,1);
y = rand(100,1);
score = rand(100,1);
figure;
colormap(flipud(bone));
caxis([0 1])
axis([0 1 0 1])
scatter(x,y,50,score,'+','LineWidth',2);
legend('scores');

I'm using the reversed 'bone' colormap which assigns pure white to score value 0 and pure black to score value 1. However, the legend seems to be automatically assigned the score 0, and so if you run the code the legend color is pure white and not visible.

Is there any ways to fix that? Thanks.


Solution

  • If you only want to plot a black + without showing the color range of the data (as with color bar) you can create a dummy legend for that. Here is how you do that:

    % plot some dummy data for the legend:
    scatter(nan,nan,[],1,'+','LineWidth',2)
    hold on
    % plot your data:
    scatter(x,y,50,score,'+','LineWidth',2);
    hold off
    % add the legend only for the first (dummy) data:
    leg = legend('scores');
    

    The result:

    enter image description here