Ha Hacker
Ha Hacker

Reputation: 407

Customized Legend in Matlab

Here I have a for loop to plot the content of my matrix.

Based on 'type' value I determine the plot object (ks,bO,rX)

for k = 1:length(data1)
    if(type(k)==1)
       h=plot(data1(k,1),data1(k,2),'ks');set(h,'linewidth',2);hold on;
    elseif(type(k) ==0)
            h=plot(data1(k,1),data1(k,2),'bO');set(h,'linewidth',2); hold on;
    else
            h=plot(data1(k,1),data1(k,2),'rX');set(h,'linewidth',2); hold on;
    end
end

I am little bit confused to find a way to put legend in my final figure, which shows my own explanation regarding each object(ks,bO,rX).

Upvotes: 2

Views: 4939

Answers (1)

nkjt
nkjt

Reputation: 7817

By default, MATLAB will see the output of this loop as not three plots but as many individual plotted points. Even though some of the points are plotted with the same settings, it doesn't automatically recognise them as part of the same series. If you give it three legend entries, it will assign them to whatever the first three points plotted were.

The simplest way around this is to change the way you plot and use logical indexing, rather than a loop:

h=plot(data1(type==1,1),data1(type==1,2),'ks'); set(h,'linewidth',2); 
hold on;
h=plot(data1(type==0,1),data1(type==0,2),'bO'); set(h,'linewidth',2);
h=plot(data1(type==-1,1),data1(type==-1,2),'rX'); set(h,'linewidth',2);

Now we have only three plots, so giving legend the three should give us the correct match between those plots (in the order they were plotted) and our labels:

legend({'Type 1'; 'Type 0' ; 'Type -1'})

Upvotes: 5

Related Questions