Aashu10
Aashu10

Reputation: 49

Plotting, marking and legend in a loop

I want to plot a graph, mark a point and write legend in a loop.

labels = {}
for i = 1: size(error,1)
    r =  plot(handles.axes1,temp(i).time,temp(i).signal);
    hold (handles.axes1, 'on')
    a = %find minimum index 
    xmin = temp(i).time(a);
    ymin = temp(i).signal(a);
    plot(handles.axes1,xmin,ymin,'ro')
    labels{end+1} = sprintf('Type : %s, %f,%f',error{i,1}.main(1,1).type,xmin,ymin)
end

grid on
legend(r, labels);

Labeling does not work, as it takes only 1st elements ignoring extra element. and the whole method is a mess with color code all messed up, is there elegant way of doing this where my legend colour matches the plot ones

Upvotes: 2

Views: 419

Answers (2)

craigim
craigim

Reputation: 3914

Another way to do this is to use the DisplayName keyword.

for i = 1:N_lines
    %...
    r(i) = plot(handles.axes1, temp(i).time, temp(i).signal, 'DisplayName', labels{i});
    %...
end
legend('show')

The advantage of doing it like this is that it attaches the name directly to the plotted point. If you are debugging, and open the plot as its being written in the plot browser, as each point get plotted the name will appear next to the point in the right-hand pane. You also don't need to keep track of a separate labels variable in case you end up later reordering your points for some reason. This way the labels always travel with their associated points.


I should add that when you call the legend command with a cell of labels, among other things it backfills 'DisplayName' so that you can still change and query it after the plot has been built even if you don't explicitly set it like I've done above. However, I find this method to be self-documenting and more convenient because it's one less thing to keep track of.

Upvotes: 4

Suever
Suever

Reputation: 65430

You need to make r an array. As it is, you're only storing the last plot handle so when you call legend it's only going to use the last plot and the first label.

% Create a unique color for each plot
colors = hsv(size(error, 1));

for i = 1:size(error, 1)
    r(i) =  plot(handles.axes1,temp(i).time,temp(i).signal, 'Color', colors(i,:));
    %...
    labels{i} = sprintf('Type : %s, %f,%f',error{i,1}.main(1,1).type,xmin,ymin);
end

legend(r, labels)

As a side-note it's best to not use i or j as your looping variable and also, don't name your variable error as that's the name of a MATLAB built-in.

Upvotes: 3

Related Questions