Raymond
Raymond

Reputation: 33

Adding Legend in Matlab

I'm trying to add a legend to my graph in Matlab.

Each colour should have a different legend, i.e., red 'r' should say upregulated, blue 'b' downregulated and green 'g' unregulated.

I've tried putting the code directly after setting the colour but this doesn't work well.

Any ideas?

function functionForNumber5(M)

fig = figure;
ax = axes('nextplot','add','xlim',[1,5],'ylim',[0,2],'xtick',           
[1:.5:5],'ytick',[0:.5:2]);
xlabel('Time (Hours)');
ylabel('Expression Level');
     for it1 = 1 : 24
     if M(5,it1) > 1.3
        currentColor = 'r';
     elseif M(5,it1) < 0.7
        currentColor = 'b';
     else
        currentColor = 'g';
     end
     plot(ax,[1:5],M(:,it1),'color',currentColor);
end

I really need a colour key to represent whether my plots are upregulated, downregulated or nonregulated, that is, 3 keys on the legend only.

Upvotes: 0

Views: 381

Answers (2)

am304
am304

Reputation: 13876

If I understand your question correctly, you have 24 lines on your graph, which are one of three colours, and you want the legend to show only those 3 colours with corresponding text. Here's a solution, which I think should work:

function functionForNumber5(M)

fig = figure;
ax = axes('nextplot','add','xlim',[1,5],'ylim',[0,2],'xtick',[1:.5:5],'ytick',[0:.5:2]);
xlabel('Time (Hours)');
ylabel('Expression Level');
h_plot = zeros(1,24); % vector of plot handles
col_idx = zeros(1,3); % vector of indices corresponding to the 3 colours
for it1 = 1 : 24
     if M(5,it1) > 1.3
        currentColor = 'r';
        col_idx(1) = it1;
     elseif M(5,it1) < 0.7
        currentColor = 'b';
        col_idx(2) = it1;
     else
        currentColor = 'g';
        col_idx(3) = it1;
     end
     h_plot(it1) = plot(ax,[1:5],M(:,it1),'color',currentColor);
end
legend(h_plot(col_idx),'upregulated','downregulated','unregulated')

Note that the code assumes that there is at least one plot of each colour, otherwise it will error out because the corresponding value of col_idx will be 0 and when used to index h_plot it won't work.

Upvotes: 1

&#193;lvaro
&#193;lvaro

Reputation: 105

There's a legend function in matlab.

x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);

figure
plot(x,y1,'-ro',x,y2,'-.b')
legend('sin(x)','cos(x)')

This would create a legend with 2 entrys one for y1 and other for y2.

Reference: http://es.mathworks.com/help/matlab/ref/legend.html#

Upvotes: 0

Related Questions